Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ErrorAttribute vs OnException vs Application_Error

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()?

like image 715
Mangesh Pimpalkar Avatar asked Jun 11 '11 19:06

Mangesh Pimpalkar


People also ask

What is HandleErrorAttribute?

ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as Controller or at the global level. The HandleError attribute is the default implementation of IExceptionFilter.

How many ways are there to handle exceptions in MVC?

In ASP.NET MVC we may have three ways to handle exceptions, Try-catch-finally. Exception filter. Application_Error event.


1 Answers

  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).

like image 66
Ivan Zlatev Avatar answered Oct 14 '22 08:10

Ivan Zlatev