dan
dan

Reputation: 5784

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?

Upvotes: 4

Views: 15543

Answers (1)

jgauffin
jgauffin

Reputation: 101176

[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/

Upvotes: 8

Related Questions