Catching unhandled exceptions in SharePoint

Published 04 February 08 06:13 PM | jannemattila 

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
 <!-- ... -->
  <httpModules>
   <clear />
   <add name="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

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Links (2/5/2008) « Steve Pietrek’s SharePoint Stuff said on February 5, 2008 9:04 PM:

PingBack from http://stevepietrekweblog.wordpress.com/2008/02/05/links-252008/

# Blog del CIIN said on February 25, 2008 7:00 PM:

Hacía tiempo que no revisaba mis RSS sobre SharePoint , y claro me ha costado ponerme al día, y aquí

# gangadhar said on March 31, 2008 3:06 AM:

I am getting error saying that The given assembly name or codebase was invalid.

# Ram said on May 7, 2008 5:31 AM:

Janne,

         We tried the same appraoch by creating a HTTPmodule hooking to Error event  and registered the same as a first module in MOSS web.config.But it did not work for us !

     Do you have any idea that what may be the cause of the issue ?

Regards,

Ram

# jannemattila said on May 7, 2008 5:37 AM:

Hi Ram!

Are you able to debug your code? I mean that if you attach your VS to the w3wp.exe process you're able to step through the lines of you handler?

J

# Asad kamran said on May 8, 2008 10:06 AM:

Janee,

But when i deployed the http module i get this error:

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047

Line 146:      <add name="MyExceptionHandler" type="MyExceptionHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=229eff298acf7a7d" />

# ed said on May 16, 2008 8:50 AM:

Thank f for that.  1st person suggesting a solution.  My inferior but workable solution was to remove the error.aspx page from the layouts folder - the application_error event then fires in global.asax and I was able to handle it there.

# ed said on May 19, 2008 3:10 AM:

Just wondering, can something similar be done for unauthorised access errors?

# Brent said on June 7, 2008 12:24 AM:

Will your saolution work when the message is

File not found?

# 天使の泪 said on September 24, 2008 10:14 AM:

http://blogs.msdn.com/jannemattila/archive/2008/02/04/catching-unhandled-exceptions-in-sharepoint.as...

# Naman said on October 22, 2008 10:35 AM:

I created the httpmodule and added the tag in Web.config.

<httpModules>

     <clear />

     <add name="SABICCustomError" type="SABICCustomError,SABICCustomError, Version=1.0.0.0, Culture=neutral, PublicKeyToken= 80a3837ac70f49e8" />

Attaching debugger and putting a breakpoint doesnt works.

Looking forward for any help.

namanc@gmail.com

# m3rd said on October 22, 2008 5:34 PM:

what can you do if you limit a survey to only one response and the user gets an error page instead of a friendly "sorry, you cannot take the survey more than once." and then return them to the home page.

# Andy Burns said on November 3, 2008 1:18 PM:

Neat! I like that.

One question though - what if I just want to use the HTTPModule to change the master page my error master page uses, rather than the simple.master it normally uses? I don't seem to be able to do that.

Or, come to that, of redirecting the error pages for a single site/url?  Hmm. Tricky.

m3rd, I suppose you could use what Janne has built above, but look at the error and if it is the survey exception, cancel the error and redirect to your own page with that message.

# Ricardo Casquete said on November 10, 2008 1:49 AM:

Nice and Elegant....

I was using before this approach which i think is worse than the one proposed by Janne

           AppDomain.CurrentDomain.UnhandledException  += new UnhandledExceptionEventHandler ( OnUnhandledException );

       private void OnUnhandledException ( object sender, UnhandledExceptionEventArgs e )

       {

           Logger.Log ( e.ExceptionObject.ToString ( ), CATEGORY_UNHANDLED_EXCEPTIONS );

       }

# drew said on November 17, 2008 3:23 PM:

I'm having trouble  implementing this.  I'm using it in conjunction with stsdev. The error never gets attached. Am I missing something? Any ideas/tips to get started?

# Steve B said on November 21, 2008 3:34 AM:

This was a nice insight into Error Handling in SharePoint and very useful.  I've implemented more-or-less your design with a few additional logical paths to decide how to handle errors based on the web.config file settings.  We also had a requirement to log any exceptions so we opted for the EventLog (which needed to be called by an elevated method call using SPSecurity) which again works perfectly.

We've had a couple of Publishing-based projects recently that have certainly benefited from this so many thanks again. ;)

# Farrukh said on February 5, 2009 12:02 PM:

Hi, I have check this approach and it works fine for me. My custom page uses simple.master (just like error.aspx). I just need to ask if there would be any way to replace simple.master with my custom.master page.

# Faarukh said on February 17, 2009 3:25 PM:

Hi,

I am able to create my on Custom Error Page with this approach, but some time it is throwing error in HTTPModule on Server.Transfer Statement. The error description is ""Error executing child request for ___.aspx". Can any body tell me regarding that. What workaround do i have to do for that. Note down that I implement this for my Custom Sharepoint (MOSS) Site.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker