Friday 19 October 2012

Elmah won't work in .NET MVC 3 won't work with CustomErrors

I've been doing a lot of work on an MVC 3 application recently, and it's already got Elmah installed ready to report all sorts of errors to help you debug your application.

Except it doesn't.

When the <customerrors /> element of the web.config is set to "On", a friendly error message appears when a user experiences an issue, but Elmah doesn't capture the error. This is because ASP.NET swallows the exception, and this method in the global.asax.cs is responsible:

This line ensures that the "handle error" attribute is attached to all controllers, and the exception's lost.

I found a really nice neat solution on a StackOverflow question, but it's a long way down the page, so I'm recording it here for easier reference.

Create a class that looks like this:

And reference it in the global.asax.cs file ahead of the other attribute like this:

The various answers and a full discussion of the problem are available at this StackOverflow question, but it's quite a long way down the page. It's really worth a read though.

No comments: