This post originated from an RSS feed registered with .NET Buzz
by Brad Wilson.
Original Post: Global Error Handling in ASP.NET
Feed Title: The .NET Guy
Feed URL: /error.aspx?aspxerrorpath=/dotnetguy/Rss.aspx
Feed Description: A personal blog about technology in general, .NET in specific, and when all else fails, the real world.
I read Craig Andera's post about global error handling in .NET, and I thought I'd give an alternative implementation for global error handling.
We use a system like this to catch all unhandled exceptions, e-mail them to the admin, log them to the Event Log, and then give the user our own version of an "Internal System Error" page.
The HttpApplication object class contains an event called Error. This event is issued whenever an unhandled exception occurs. The exception that has been thrown is available via Server.GetLastError(). The easiest way to do this is by making a new class that overrides IHttpModule and registering it in Web.config, like so:
public class MyModule : IHttpModule {
private HttpApplication _application;
void IHttpModule.Init(HttpApplication application) {
_application = application;
_application.Event += new EventHandler(ErrorHandler);
}
private void ErrorHandler(Object sender, EventArgs e) {
Exception ex = _application.Server.GetLastError();
// deal with ex as you see fit
// To prevent ASP.NET's error page, call:
// _application.Server.ClearError();
}
}
If you deal with the error and present your own content, you can call ClearError() as shown above. This tells the system that you've handled the error (perhaps by giving a custom error page), so it won't provide its default error handler page. If, on the other hand, you just want to log the error and let the system error go through (like we do in debug mode, since it contains valuable exception and stack trace info), then don't call ClearError().
Also, this will catch HTTP errors that might be thrown by the ASP.NET system itself, such as 404s or 500s (in which case, ex will be an HttpException). We route all calls through ASP.NET, so this also gives us a convenient place to give out our own 403, 404, and 500 messages.
It's not quite as elegant as a try/catch block, but it doesn't require you to change any class hierarchy. :)