ErrorAttribute vs OnException vs Application_Error

Mangesh Pimpalkar picture Mangesh Pimpalkar · Jun 11, 2011 · Viewed 8.3k times · Source

I want to handle application wide error and show a ErrorView page in asp.net mvc. There are 3 ways to do it (or i know).

1) ErrorAttribute in BaseController:Controller class.
     Can be used on individual Action/Controller/BaseController.
2) Override OnException() in the BaseController:Controller class.
     Will work on Controllers derived from BaseController
3) Application_Error in Global_aspx.

What is the best practice. Which one of these methods should be used for application wide error handling or should we use multiple or only one.

If we handle error on ErrorAttribute Or/And OnException() on BaseController should we still handle it in Application_Error().

When should we use Application_Error()?

Answer

Ivan Zlatev picture Ivan Zlatev · Jun 11, 2011
  1. HandleErrorAttribute is an MVC filter applied via the attribute. You can supply a view name to display if an exception occurs and you can also specify the base (or specific) type of exception this filter applies to. If no view name is supplied it will look for a view named "Error". As you've already noticed you can apply it to various scopes. It allows you to specify a different "error page" view based on the exception.

  2. Controller.OnException is a method that will get called if any of your actions ends up throwing an error.

  3. Both of the above two are MVC concepts and part of the MVC pipeline, which sits on top of the ASP.NET pipeline, and if you handle the exception using the above it won't propagate to Application_Error, but things like http errors 404, 500 and will if I remember correctly.

What to use?

Definitely look into ELMAH for application wide error logging and my blog post about ELMAH and ASP.NET MVC

Regarding displaying error pages you should be fine with just using [HandleError] and the HandleErrorAttribute, since it already handles everything for you (optional filtering and optional custom error page per exception type).