Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best practice for global error/exception handling in ASP.NET MVC?

I've seen two methods of implementing global error handling in an ASP.NET MVC 3 application. One method is via the Application_Error method in Global.asax.cs.

For example (Error Handling in global.asax):

public class SomeWebApplication : System.Web.HttpApplication {

  // ... other methods ...

  protected void Application_Error() {
    // ... application error handling code ...
  }
}

The other method is via a [HandleError] action filter attribute registered in the RegisterGlobalFilters method, again in Global.asax.cs.

Which is the better way to approach this? Are there any significant disadvantages to either approach?

like image 970
dan Avatar asked Feb 23 '23 22:02

dan


1 Answers

[HandleError] is the way to go since it keeps everything simple and responsibility is clear. This action filter is a specific ASP.NET MVC feature and therefore is the official way of handling errors. It's also quite easy to override the filter to add custom functionality.

Application_Error is the old way to do it and doesn't really belong in MVC.

The [HandleError] attribute works fine as long as you remember to tag your controllers (or the base controller) with it.

Update:

Created a blog entry: http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/

like image 77
jgauffin Avatar answered May 04 '23 19:05

jgauffin