Tuesday 8 June 2010

Handling Unexpected Exceptions in ASP.Net MVC

There are way too many yellow screens of death out there on the net for my liking. But rather than trying to bullet proof your MVC web apps by putting try catch blocks in all your MVC actions to handle unexpected exceptions, there is a far easier way to do it and it keeps your code nice and DRY - see my code snippet below:

public class BaseController : Controller
{
 
 protected override void OnException(ExceptionContext filterContext)
 {
  // Record the error
  Log.Error("Unexpected error in controller", filterContext.Exception);

  // Uses customErrors element from web.config
  if (filterContext.HttpContext.IsCustomErrorEnabled)
  {
   // Set exception as handled and status code 500
   filterContext.ExceptionHandled = true;
   filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

   this.View("Error").ExecuteResult(this.ControllerContext);
  }
 }

}

I override the OnException method within a base controller for my other controllers to inherit from. Any unhandled exceptions in my action methods will hit this and I can gracefully log the exceptions and send the user to a helpful error view (as long as customErrors for the app are set to true) - it's worth noting I also set an appropriate HTTP status code :)

3 comments:

  1. This is an excellent post.

    Very helpful and saved my bacon.

    You hero.

    ReplyDelete
  2. Hey! thanks for useful review. It was easy to read, but I'd like to add that if your business needs to be updated try outsource software development services.

    ReplyDelete
  3. Thanks for mentioning this. Many casino affiliates look for fresh best affiliate casino program at such comparison online gaming websites.

    ReplyDelete