MVC3 brings a new set of features to error handling, letting exceptions be dealt with in the MVC pipeline. You need to implement a few strands of these to cover your bases so lets look at how you hook up 404, 500′s and logging.
500 errors aka ZOMG its all gone wrong.
So firstly the global.asax.cs is used to add error handling filters to each controller using the new HandleErrorAttribute wrapped in a globalfilters method.
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute { ExceptionType = typeof(HttpException), Order = 2, }); filters.Add(new HandleErrorAttribute { ExceptionType = typeof(HttpCompileException), Order = 3 }); filters.Add(new HandleErrorAttribute()); }
As you can see these a type, order (and view but it defaults to error page so alls well). So within the MVC pipeline the error is swiftly despatched to the appropriate view.
404′s ZOMG you want what?
404 uses the web.config to point to a errorhandler controller in the global project that sends you to a view. This is suspiciously simple and is a work in progress as on previous projects we’ve been writing custom http handlers to take care of this.
<customErrors mode="On"> <error statusCode="404" redirect="~/error/notfound"></error> </customErrors>
Logging
When logging gets involved (ELMAH or Codesmith rock here possibly codesmith as its apprently more MVC3 friendly) it will utilise the following class.
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //do some logging } }