Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Article

An HTTP Module for ASP.NET Error Handling

Rate me:
Please Sign up or sign in to vote.
3.71/5 (10 votes)
31 Oct 20061 min read 150.4K   1.1K   49   18
A simple HTTP module to be used as a "last-resort" error handler for ASP.NET applications. It does not require changes to existing code, and can be "dropped-in" to an already running site.

Introduction

I wrote this HTTP module for a client to plug in an existing site which was having intermittent errors while undergoing integration testing. The client wanted something that could capture the basic error information along with the request query-string/form parameters and write it out. All this needed to be done without modifying the existing code.

Although the existing code did have regular try-catch error handlers in the code-behind files, not all errors were handled properly, and in some cases, the code in the catch block itself was error-prone. Initially, I thought of using a custom error page. However, in view of issues regarding getting the correct context of errors, I decided to use an HTTP module.

The code

The code itself is pretty straightforward.

Step 1 is to wire an event handler for the Error event:

C#
public void Init (HttpApplication app)
{
   app.Error += new System.EventHandler (OnError);
}

Step 2 involves writing the actual event handler to write out the error message and the request form / query-string parameters:

C#
public void OnError (object obj, EventArgs args)
{
   // At this point we have information about the error
   
   HttpContext ctx = HttpContext.Current;
   HttpResponse response = ctx.Response;
   HttpRequest request = ctx.Request;

   Exception exception = ctx.Server.GetLastError();

   response.Write("Your request could not processed. " + 
                  "Please press the back button on" + 
                  " your browser and try again.<br/>");
   response.Write("If the problem persists, please " + 
                  "contact technical support<p/>");
   response.Write("Information below is for " + 
                  "technical support:<p/>");
   
   string errorInfo = "<p/>URL: " + ctx.Request.Url.ToString (); 
  errorInfo += "<p/>Stacktrace:---<br/>" + 
     exception.InnerException.StackTrace.ToString();
  errorInfo += "<p/>Error Message:<br/>" + 
     exception.InnerException.Message;

   //Write out the query string 
   response.Write("Querystring:<p/>");

   for(int i=0;i<request.QueryString.Count;i++)
   {
    response.Write("<br/>" + 
         request.QueryString.Keys[i].ToString() + " :--" + 
         request.QueryString[i].ToString() + "--<br/>");// + nvc.
   }

   //Write out the form collection
   response.Write("<p>---------------" + 
                  "----------<p/>Form:<p/>");

   for(int i=0;i<request.Form.Count;i++)
   {
    response.Write("<br/>" + 
             request.Form.Keys[i].ToString() + 
             " :--" + request.Form[i].ToString() + 
             "--<br/>");// + nvc.
   }

   response.Write("<p>-----------------" + 
                  "--------<p/>ErrorInfo:<p/>");

   response.Write (errorInfo);

   // --------------------------------------------------
   // To let the page finish running we clear the error
   // --------------------------------------------------
   
   ctx.Server.ClearError ();
}

Deployment:

To deploy this HTTP module, simply drop the compiled DLL in the bin folder and make this entry in the web.config to register it:

XML
<system.web>  

    <!-- Add the lines below to register the http module -->    
    <httpModules>
        <add type="MyApps.Utilities.GlobalErrorHandler,
                      GlobalErrorHandler" 
                name="GlobalErrorHandler" />
    </httpModules>  

</system.web>

Download

You can download the complete source code (.cs file), a sample web.config, and the compiled DLL in a single zip file GlobalErrorHandler.zip from the link above.

Further Improvements

This code was really a result of a couple of hours work, so it can obviously be refined. A few changes I am already considering: make the display text dynamic and the overall display more customizable via web.config. In addition, an option to email or log the error messages would be useful. I will be posting updated code in the next few weeks.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Eeraj is a software developer working in the USA. He has over 10 years of experience and his interests include ASP.NET, JavaScript, C#, Data Mining and Business Intelligence. You can visit his website at http://www.interviewboard.com

Comments and Discussions

 
QuestionNot handling the unhandled Error Pin
Senthilaan13-Jul-14 21:59
professionalSenthilaan13-Jul-14 21:59 
GeneralMy vote of 5 Pin
arindamrudra5-Jul-12 23:53
professionalarindamrudra5-Jul-12 23:53 
GeneralIIS 7.5 .Error event not firing Pin
ilia.broudno15-Feb-11 8:49
ilia.broudno15-Feb-11 8:49 
GeneralRe: IIS 7.5 .Error event not firing Pin
Gary Huck4-Apr-12 8:11
Gary Huck4-Apr-12 8:11 
QuestionI am gettting the following error which using the code Pin
Prakash.SE5-Jul-07 22:41
Prakash.SE5-Jul-07 22:41 
GeneralThis is a lot simple and shorter then yours... Pin
hakervytas16-Mar-07 5:08
hakervytas16-Mar-07 5:08 
Generalthank you very much Pin
riali27-Nov-06 10:54
riali27-Nov-06 10:54 
QuestionWhich references should I load Pin
riali27-Nov-06 7:45
riali27-Nov-06 7:45 
AnswerRe: Which references should I load Pin
eeraj27-Nov-06 8:16
eeraj27-Nov-06 8:16 
If you are using VS.NET, you need to reference System.Web.dll

Alternatively, if you do not want to use Visual Studio, you can edit the code in notepad and open up Visual Studio command prompt (Program File --> Microsoft Visual Studio 2003/2005 -->VS.NET 2003/2005 Tools-->VS.NET command prompt), navigate to the folder containing the .cs file and type:

csc /t:library /out:GlobalErrorHandler.dll *.cs

This will compile the code as well.

- eeraj
http://www.interviewboard.com
Questionmaking a dll Pin
riali25-Nov-06 3:59
riali25-Nov-06 3:59 
AnswerRe: making a dll Pin
eeraj27-Nov-06 4:48
eeraj27-Nov-06 4:48 
GeneralThe idea is sound but the implementation is potentially a security flaw Pin
toepoke7-Nov-06 10:10
toepoke7-Nov-06 10:10 
GeneralRe: The idea is sound but the implementation is potentially a security flaw Pin
eeraj7-Nov-06 10:21
eeraj7-Nov-06 10:21 
GeneralRe: The idea is sound but the implementation is potentially a security flaw Pin
toepoke7-Nov-06 10:39
toepoke7-Nov-06 10:39 
GeneralThere is a ready solution from microsoft Pin
Evyatar Ben-Shitrit6-Nov-06 22:10
Evyatar Ben-Shitrit6-Nov-06 22:10 
GeneralRe: There is a ready solution from microsoft Pin
eeraj7-Nov-06 3:40
eeraj7-Nov-06 3:40 
Generalgood Pin
dinolee31-Oct-06 17:46
dinolee31-Oct-06 17:46 

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

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