So, what else is new in MVC 3?
MVC 3 now has a GlobalFilterCollection that is automatically populated with a HandleErrorAttribute. This default FilterAttribute brings with it a new way of handling errors in your web applications. In short, you can now handle errors inside of the MVC pipeline.
What does that mean?
This gives you direct programmatic control over handling your 500 errors in the same way that ASP.NET and CustomErrors give you configurable control of handling your HTTP error codes.
How does that work out?
Think of it as a routing table specifically for your Exceptions, it's pretty sweet!
Global Filters
The new Global.asax file now has a RegisterGlobalFilters method that is used to add filters to the new GlobalFilterCollection, statically located at System.Web.Mvc.GlobalFilter.Filters. By default this method adds one filter, the HandleErrorAttribute.
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
HandleErrorAttributes
The HandleErrorAttribute is pretty simple in concept: MVC has already adjusted us to using Filter attributes for our AcceptVerbs and RequiresAuthorization, now we are going to use them for (as the name implies) error handling, and we are going to do so on a (also as the name implies) global scale.
The HandleErrorAttribute has properties for ExceptionType, View, and Master. The ExceptionType allows you to specify what exception that attribute should handle. The View allows you to specify which error view (page) you want it to redirect to. Last but not least, the Master allows you to control which master page (or as Razor refers to them, Layout) you want to render with, even if that means overriding the default layout specified in the view itself.
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute
{
ExceptionType = typeof(DbException),
// DbError.cshtml is a view in the Shared folder.
View = "DbError",
Order = 2
});
filters.Add(new HandleErrorAttribute());
}
Error Views
All of your views still work like they did in the previous version of MVC (except of course that they can now use the Razor engine). However, a view that is used to render an error can not have a specified model! This is because they already have a model, and that is System.Web.Mvc.HandleErrorInfo
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "DbError";
}
<h2>A Database Error Has Occurred</h2>
@if (Model != null)
{
<p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p>
}
Errors Outside of the MVC Pipeline
The HandleErrorAttribute will only handle errors that happen inside of the MVC pipeline, better known as 500 errors. Errors outside of the MVC pipeline are still handled the way they have always been with ASP.NET. You turn on custom errors, specify error codes and paths to error pages, etc.
It is important to remember that these will happen for anything and everything outside of what the HandleErrorAttribute handles. Also, these will happen whenever an error is not handled with the HandleErrorAttribute from inside of the pipeline.
<system.web>
<customErrors mode="On" defaultRedirect="~/error">
<error statusCode="404" redirect="~/error/notfound"></error>
</customErrors>
Sample Controllers
public class ExampleController : Controller
{
public ActionResult Exception()
{
throw new ArgumentNullException();
}
public ActionResult Db()
{
// Inherits from DbException
throw new MyDbException();
}
}
public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult NotFound()
{
return View();
}
}
Putting It All Together
If we have all the code above included in our MVC 3 project, here is how the following scenario's will play out:
- A controller action throws an Exception.
- You will remain on the current page and the global HandleErrorAttributes will render the Error view.
- A controller action throws any type of DbException.
- You will remain on the current page and the global HandleErrorAttributes will render the DbError view.
- Go to a non-existent page.
- You will be redirect to the Error controller's NotFound action by the CustomErrors configuration for HTTP StatusCode 404.
But don't take my word for it, download the sample project and try it yourself.
Three Important Lessons Learned
For the most part this is all pretty straight forward, but there are a few gotcha's that you should remember to watch out for:
1) Error views have models, but they must be of type HandleErrorInfo.
It is confusing at first to think that you can't control the M in an MVC page, but it's for a good reason. Errors can come from any action in any controller, and no redirect is taking place, so the view engine is just going to render an error view with the only data it has: The HandleError Info model. Do not try to set the model on your error page or pass in a different object through a controller action, it will just blow up and cause a second exception after your first exception!
2) When the HandleErrorAttribute renders a page, it does not pass through a controller or an action.
The standard web.config CustomErrors literally redirect a failed request to a new page. The HandleErrorAttribute is just rendering a view, so it is not going to pass through a controller action. But that's ok! Remember, a controller's job is to get the model for a view, but an error already has a model ready to give to the view, thus there is no need to pass through a controller.
That being said, the normal ASP.NET custom errors still need to route through controllers. So if you want to share an error page between the HandleErrorAttribute and your web.config redirects, you will need to create a controller action and route for it. But then when you render that error view from your action, you can only use the HandlerErrorInfo model or ViewData dictionary to populate your page.
3) The HandleErrorAttribute obeys if CustomErrors are on or off, but does not use their redirects.
If you turn CustomErrors off in your web.config, the HandleErrorAttributes will stop handling errors. However, that is the only configuration these two mechanisms share. The HandleErrorAttribute will not use your defaultRedirect property, or any other errors registered with customer errors.
In Summary
The HandleErrorAttribute is for displaying 500 errors that were caused by exceptions inside of the MVC pipeline. The custom errors are for redirecting from error pages caused by other HTTP codes.
Also, if you are going to be handling all these errors, why not report them too?