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

An HTTP Module for ASP.NET Error Handling

, 31 Oct 2006
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

<system.web>  

    <!--<span class="code-comment"> Add the lines below to register the http module --></span>    
    <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

Share

About the Author

eeraj
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

 
You must Sign In to use this message board.
    Spacing  Noise  Layout  Per page   
QuestionNot handling the unhandled Error [modified]memberSenthilaan13-Jul-14 22:59 
Hi,
 
I followed the same way as you mentioned but when i tried catch an unhandled error it is not working. I just added the code as below in load part of a page, its going to the line where error occurs. What am i missing here?
 

protected void Page_Load(object sender, EventArgs e)
{
    int x = 0; int y = 100;
    Response.Write(Convert.ToString(y / x));
}
 
Thanks in advance..!

modified 14-Jul-14 4:15am.

GeneralMy vote of 5memberarindamrudra6-Jul-12 0:53 
Awesome
GeneralIIS 7.5 .Error event not firingmemberilia.broudno15-Feb-11 9:49 
This does not seem to work for me.
I am running IIS 7.5 on Windows 7.
I have an IHttpModule that captures some other events I need (Authentication) and I have an ASP.NET application that generates an error.
I can capture this error in Global.asax with Application_Error event handler, I can capture it with Page_Error event handler on the page, but when I remove both of those and want to capture it in the HttpModule, it does not get captured.
I put breakpoints in the module to make sure it is not some sort of misconfiguration and it does stop in AuthenticateRequest handler, but not in Error handler.
For reference this is my code:
public void Init(HttpApplication context)
{
context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
context.Error += new EventHandler(context_Error);
................
 
Help?
GeneralRe: IIS 7.5 .Error event not firingmemberGamleKoder4-Apr-12 9:11 
I got his code to work with the following change - I removed the ",GlobalErrorHandler" from the type= portion of the add. Ie:
<add type="MyApps.Utilities.GlobalErrorHandler" name="GlobalErrorHandler" />
 
I don't even know what the 2nd param is in the type=""...
QuestionI am gettting the following error which using the codememberPrakash.SE5-Jul-07 23:41 
I am gettting the following error which using the code:
 
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
 
Parser Error Message: File or assembly name GlobalErrorHandler, or one of its dependencies, was not found.
 
Source Error:
 

Line 113:
Line 114:
Line 115:
Line 116:

Line 117: <!-- DYNAMIC DEBUG COMPILATION


 
Prakash G, Software Engineer
Iridium Interactive Limited,
SriNagar Colony
Road #3 Banjara Hills
Hyderabad - 500035
mail me @ [email protected]
call me @ +91 9866833523

GeneralThis is a lot simple and shorter then yours...memberhakervytas16-Mar-07 6:08 
Your article not usefull for unhandled exceptions, look that older article then yours for ASP.NET 1.1 and for ASP.NET 2.0 works too link
 
Also if you developer on ASP.NET 2.0 just nead add few lines of code in web.config file, like that, on the end of file before :

<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="your email">
<network host="smtp.domain" port="25" userName="your email or username" password="your password"/>
</smtp>
</mailSettings>
</system.net>

 
This code example send to your email any detailed exceptions.
Generalthank you very muchmemberriali27-Nov-06 11:54 
it works and I've Smile | :) learned again
 
riali

QuestionWhich references should I loadmemberriali27-Nov-06 8:45 
Error 1 The type or namespace name 'IHttpModule' could not be found (are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'HttpApplication' could not be found (are you missing a using directive or an assembly reference?)

 
riali

AnswerRe: Which references should I loadmembereeraj27-Nov-06 9: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 dllmemberriali25-Nov-06 4:59 
how can i change the messages and make a new dll?
 
riali

AnswerRe: making a dllmembereeraj27-Nov-06 5:48 
The mesasages that you see are generated by the response.write statements. You can modify the response.write code blocks to customize your message. Compiling to a new dll is straightforward - download the source code, modify the response.write and use csc.exe (or create a VS.NET class library projectand compile from IDE) to compile the dll.
GeneralThe idea is sound but the implementation is potentially a security flawmemberleapoflogic7-Nov-06 11:10 
Nice article I've used a similar system myself, but you should really be wiring up your code to the customErrors tag in web.config. Or place your debug code in the event log (as suggested above) and give your users a friendly message.
 
The way you're reporting your debug code at the moment will display to the end user giving any potential hacker information on how your system works.
GeneralRe: The idea is sound but the implementation is potentially a security flawmembereeraj7-Nov-06 11:21 
Your point is valid and I should have pointed it out clearly in my article - it is never a good idea to display the error stacktrace or all of form/querystring parameters in a production system. This is true irrespective of which method one uses for error handling.
 
I used this module on an internal QA site. It is actually quite trivial to modify the code in the HTTP module to display the friendly messages and write the actual info to a secure log.
GeneralRe: The idea is sound but the implementation is potentially a security flawmemberleapoflogic7-Nov-06 11:39 
Good to hear, but thought best to mention to anyone reading it who may consider using it on a public facing site.
 
Regards,
Chitty.
GeneralThere is a ready solution from microsoftmemberEvyatar Ben-Shitrit6-Nov-06 23:10 
http://support.microsoft.com/?id=911816[^]
 
Evyatar Ben-Shitrit

GeneralRe: There is a ready solution from microsoftmembereeraj7-Nov-06 4:40 
That solution not capture the form or querystring parameters and if you read it carefully, it is designed for ASP.NET 2.0. Also, for any given solution/code sample on any web site, there will be an alternate solution available on many other web sites. So in effect, all problems already have a solution.
Generalgoodmemberdino66631-Oct-06 18:46 
干得不错

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 31 Oct 2006
Article Copyright 2006 by eeraj
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid