Catching unhandled exceptions in SharePoint

If you have done some dev stuff with MOSS you have most likely seen this:

UnexpectedError

"An unexpected error has occurred. " is something that you probably don't want to see at your browser.... you 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 if you want to do customized approach then you can take HttpModule approach which I'm going to go through in this post.

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

 12345678910111213141516171819202122232425262728
 using System;using System.Web;public class MyExceptionHandler : IHttpModule{  public void Dispose()  {  }  public void Init(HttpApplication context)  {    context.Error += new EventHandler(context_Error);  }  void context_Error(object sender, EventArgs e)  {    Exception[] unhandledExceptions = HttpContext.Current.AllErrors;    foreach (Exception ex in unhandledExceptions)    {      // TODO: log your errors    }    HttpContext.Current.Server.ClearError();    HttpContext.Current.Response.Clear();    HttpContext.Current.Server.Transfer("/_layouts/MyCustomErrorPage.aspx");  }}

You can probably see from the code that I'll attach my code to the Error event and in my event I'll do some basic stuff and then transfer to my MyCustomErrorPage.aspx. I used Server.Transfer just because I want user to stay at the same url where exception happened. If I would use Response.Redirect it would "change" the url at the users browser. Same "change" would happen if your custom error page would be normal SharePoint publishing page (i.e. /Pages/MyCustomErrorPage.aspx). If the url stays the same the user can actually press F5 and retry the operation right away. 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. I'll let you decide what you want :-) So do some testing and then decide what's good for you.

But one 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:

 12345678910111213
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><configuration> <!-- ... -->  <httpModules>   <clear />    < addname="MyExceptionHandler"type=" MyExceptionHandler,Example,       Version=1.0.0.0, Culture=neutral,PublicKeyToken=34a2bd01f6f6eb10"   />    <add name="SPRequest" type="Microsoft.SharePoint.ApplicationRuntime.SPRequestModule,       Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />   <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />   <!-- ... -->  </configuration

See line 6 where I put my exception handler definition.

Anyways... Happy hacking!

J