Handling Error "Centrally" in a SharePoint Application

It will be nice if SharePoint displays all types of error message on a custom screen. And certainly it's possible. This sample shows how to handle errors centrally in a SharePoint.

In MOSS, you most likely have seen this screen:
"An unexpected error has occurred." is something that you probably don't want in your application. We want to have customized error page. In ASP.NET application you normally put Application_Error into you global.asax file. However in SharePoint that place has been taken by the product itself :-) So for customized approach we can take HttpModule approach.

So let's create our custom exception handler http module. Here's the code for that:

From the code we'll attach my code to the Error event and in my event we'll do some basic stuff and then transfer it to my MyCustomErrorPage.aspx. I used Server.Transfer just because I want user to stay at the same url where exception happened. If the url stays the same the user can actually press F5 and retry the operation. Of course it can be bad thing too and you may want to redirect to another page to avoid creating the same exception all over again. You decide what you want :-) So do some testing and then decide what's good for you.
Important thing to notice. You need to put your IHttpModule before SharePoint specific modules in your web.config or otherwise your error routines may not work as you would expect. Here's example from that:

For Reference :