Click here to Skip to main content
Click here to Skip to main content

Handling Error Centrally in a SharePoint Application

, 20 May 2008
Rate this:
Please Sign up or sign in to vote.
An article on handling errors centrally in a SharePoint application, using IHttpModule.

Introduction

It is always nice if SharePoint also displays all types of error message in a friendly screen like other ASP.NET projects do. And it is possible in a very easy way. This sample code shows how to handle errors centrally in a SharePoint application. Well, this technique also applies for other ASP.NET projects. And, this is a better technique than handling errors in Global.aspx. I have also used the Logging Application Block of the Microsoft Enterprise Library to log errors in to a file.

Problem

Many SharePoint developers face a problem when they want to handle errors centrally. In any ASP.NET application, it is an easy task; we can simply handle errors from the Application_Error function in the Global.aspx file; But in SharePoint, it never reaches that function. I have seen other developers struggling to make it work in different ways; so I decided to take a different approach.

Solution

To solve the problem, I have implemented an IHttpModule interface and used the DLL in my project. An HTTP module is called on every request in response to the BeginRequest and EndRequest events. As a result, the module runs before and after a request is processed.

By using the IHttpModule, we can not only do error handling, but also lots of other things. If the ASP.NET application is running under IIS 6.0, we can use the HTTP modules to customize requests for resources that are serviced by ASP.NET. This includes ASP.NET Web pages (.aspx files), Web services (.asmx files), ASP.NET handlers (.ashx files), and any file type that we have mapped to ASP.NET. If the ASP.NET application is running under IIS 7.0, we can use HTTP modules to customize requests for resources that are served by the IIS. This includes not just ASP.NET resources, but HTML files (.htm or .html files), graphics files, and so on.

Understanding the Code

Let’s jump into the code. In the ErrorModule class, the Init function is called with the HttpApplication object. This object contains information about our application. We can do lots of useful things with this object. But for our problem, we only need to attach an event handler to the HttpApplication.Error event.

Context.Error += new EventHandler(Application_Error);

Now, we will do the main coding in the Application_Error function:

public void Application_Error(object sender, EventArgs e)
{            
   HttpContext Context = HttpContext.Current;
   Exception exception;
   for (exception = Context.Server.GetLastError(); 
        exception.InnerException != null; 
        exception = exception.InnerException) { }

   String code = DateTime.Now.ToString("ddMMyyyy-HHmmfff");
   String Message = exception.Message + Environment.NewLine + 
                    "Stack Trace: " + exception.StackTrace;

   Logger.Write(Message, "General",5, 1, 
                System.Diagnostics.TraceEventType.Critical, code);  
        
   HttpContext.Current.Application.Add("ErrorCode", code);
   HttpContext.Current.Application.Add("LastException", exception);

   String CustomErrorPagePath = 
     System.Configuration.ConfigurationManager.AppSettings["CustomErrorPagePath"];

   ((System.Web.HttpApplication)(sender)).Response.Redirect(CustomErrorPagePath);
}

In this function, we have to first take the instance of HttpContext. From this object, we can get the exception information. And we will then get the last exception object. We now loop through that exception object to go down in depth and find the first error that raised the exception.

for (exception = Context.Server.GetLastError(); 
     exception.InnerException != null; 
     exception = exception.InnerException) { }

Next, we generate an error code. This is for a reference that the application user will see in their error page and which they can use to call the support team with. The support team can search the log file with the error code, and can determine what actually caused the error by looking at the stack trace.

Here, I am creating the error message with the error info and the stack trace. And the following code tells the Microsoft Enterprise Library’s Logging Application Block to log the error:

Logger.Write(Message, "General",5, 1, 
       System.Diagnostics.TraceEventType.Critical, code);

We can also configure whether we want to keep the log in a database, or in a flat file, or in other places. Now, we need to save the error so that we can show it in a custom error page. The following code saves the error code and the exception object in the HttpApplicationState:

HttpContext.Current.Application.Add("ErrorCode", code);
HttpContext.Current.Application.Add("LastException", exception);

Now, we have to redirect to the custom error page. For this, we first read the URL from the configuration file and redirect to that page.

String customErrorPage = 
  System.Configuration.ConfigurationManager.AppSettings["CustomErrorPage"];
((System.Web.HttpApplication)(sender)).Response.Redirect(customErrorPage);

From the custom error page, first we have to get the exception object and the error code that we have saved.

Exception ex = (Exception)HttpContext.Current.Application.Get("LastException");
String Code = (string)HttpContext.Current.Application.Get("ErrorCode");

And then, we need to show the error message in a label or some another control in a nice way.

Configuration & Deployment

After compiling the project, we need to put the CentralErrorHandler.dll to the GAC, either by using gacutil or just by dragging the DLL to the folder C:\WINDOWS\assembly.

And to enable the application to use our newly created ErrorModule, we need to update the web.config file of our SharePoint application and put the following lines:

<system.web>
   <httpModules>
     <add name="MyErrorHandler" type="CentralErrorHandler.ErrorModule, 
                                      CentralErrorHandler, Version=1.0.0.0, 
                                      Culture=neutral, PublicKeyToken=06a3e095a0c5fc38 " />
   </httpModules>
</system.web>

We also need to add the CustomErrorPagePath to redirect to our custom error page.

<appSettings>
   <add key="CustomErrorPagePath" value="http://MySharePointSite/MyErrorHandler.aspx" />
</appSettings>

As I said earlier, we can also configure where we want to log the error message, and what the format of our error logging should be. The following configuration is for writing the error in a file:

<configuration>
  
  <configSections>
    <section name="loggingConfiguration" 
       type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, 
             Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, 
             Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>

  <loggingConfiguration name="Logging Application Block" tracingEnabled="true" 
            defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add fileName="C:\trace.log" header="----------------------------------------" 
           footer="----------------------------------------" 
           formatter="Text Formatter" 
           listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.
                             FlatFileTraceListenerData, 
                             Microsoft.Practices.EnterpriseLibrary.Logging, 
                             Version=3.1.0.0, Culture=neutral, 
                             PublicKeyToken=b03f5f7f11d50a3a" 
           traceOutputOptions="None"
           type="Microsoft.Practices.EnterpriseLibrary.
                 Logging.TraceListeners.FlatFileTraceListener, 
                 Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, 
                 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
           name="FlatFile TraceListener" />
   ..................
   ..................
  </loggingConfiguration>

</configuration>

For more information about formatting error messages and configuring the destination of the Logging Application Block, please take help from MSDN. We also need to put the MyErrorHandler.aspx and MyErrorHandler.aspx.cs files to a SharePoint site virtual path (e.g., C:\Inetpub\wwwroot\wss\ MySharePointSite).

References

To know more about the Logging Application Block, IHttpModule, and HttpApplication, you can go through the following links.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Anupam Ranku
Software Developer (Senior) Gen-i, Australia
Australia Australia
Expertise area: ASP.NET, C#, Microsoft Office SharePoint 2010 & 2007, Web Service, Windows-based Applications etc.
 
Blog: http://mydevdiary.blogspot.com/

Comments and Discussions

 
GeneralException/Error Handling.... Pinmemberidltsa22-Aug-08 3:36 
GeneralRe: Exception/Error Handling.... PinmemberAnupam Ranku22-Aug-08 7:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 20 May 2008
Article Copyright 2008 by Anupam Ranku
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid