Error Handling in asp.net mvc 3

Shawn Mclean picture Shawn Mclean · May 13, 2011 · Viewed 21.9k times · Source

Is there a built in or a proper way to handle errors in asp.net mvc 3?

This is what I want to do:

  1. If the application crashes, or throws an error, it goes to a specific error page.
  2. I can throw my own error from the controller action. (and it goes to an error page).

I found the following ways:

  1. I see there is a long way to do it here. (for v1 and v2 but also applies to v3).
  2. Using errorhandle attribute here.

How do I handle this the proper way?

If the solution is similar or is like #1 in the list above, I am using ninject and I have not created a base class. How do I still do this?

Answer

Jerad Rose picture Jerad Rose · May 13, 2011

I would suggest implementing a custom HandleErrorAttribute action filter.

See this link for more details:
http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx

Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.

Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.

UPDATE:

Per some questions below, here is an example of a HandleJsonErrorAttribute that I use:

public class HandleJsonErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var serviceException = filterContext.Exception as ServiceException;

        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };

        filterContext.ExceptionHandled = true;
    }
}

And here is the jQuery that I use to handle these unhanded exceptions:

$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
    showPopdown($.parseJSON(jqXHR.responseText).message);
});

This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.

Also, in my implementation, I have a custom ServiceException that I throw from services, and this sends the message from the service layer instead of a generic message.