Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices when reporting exception messages to the user

In my ASP.NET MVC application, I do not want to report all exception messages to the user. But there are certain types of exceptions that I'd like to report to the user, so I created an action filter to decide if it's this particular type of exception, and if so then display the exception's message, otherwise display a generic message. So I created a custom exception called ClientException.

My filter looks something like this:

    if (filterContext.Exception is ClientException)
         message = filterContext.Exception.Message.Replace("\r", " ").Replace("\n", " ");
   else
        message = "An error occured while attemting to perform the last action.  Sorry for the inconvenience.";

    filterContext.HttpContext.Response.Status = "500 " + message;

I read this http://blogs.msdn.com/b/kcwalina/archive/2007/01/30/exceptionhierarchies.aspx where the author recommends using existing .NET exception types to report usage errors. However, by introducing my custom exception, I just have to do a single check in my filter. Is my approach okay?

like image 729
Prabhu Avatar asked Mar 04 '11 18:03

Prabhu


1 Answers

I like this approach for a couple of reasons.

First, it fails safely. If someone doesn't explicity throw a ClientException, then the exception details are not reported. Forgetting to display something is a lesser problem than accidently displaying something.

Secondly, it allows the decision about whether to display the exception to be made at the proper place. Not all IOExceptions are displayed, for example. Some may be, and others wont be. The specific exceptions can be caught and transformed anywhere in the call stack, so that tranformation can be made at a place where it is known to be correct.

Both of those things together mean that a future developer will not innappropriately change a whole class of exception to be displayed, or think that something won't be displayed when it actually will be.

Also, the purpose of the using a particular exception type is to determine later what action to take in response to that exception. "Display this message to the user" is a perfectly good action to specify. Once that decision has been made, then the exact nature of the exception is completely irrelivant. (The original problem may be put in the InnerException property, for logging purposes, of course.)

So, in my opinion, this is a good design.

like image 109
Jeffrey L Whitledge Avatar answered Sep 18 '22 01:09

Jeffrey L Whitledge