ASP.Net Handling Errors In An HttpModule

HTTP modules are an integral part of the ASP.NET pipeline model. Suffice it to say that they act as content filters. An HTTP module class implements the IHttpModule interface . With the help of HttpModules you can pre- and post-process a request and modify its content. IHttpModule is a simple interface:

public interface IHttpModule
{
void Dispose();
void Init(HttpApplication context);
}

As you see the context parameter is of type HttpApplication. It will come in very handy when we write out own HttpModule. Implementation of a simple HttpModule may look as follows:

using System;
using System.Web;

namespace AspNetResources.CustomErrors
{
public class MyErrorModule : IHttpModule
{
public void Init (HttpApplication app)
{
app.Error += new System.EventHandler (OnError);
}

public void OnError (object obj, EventArgs args)
{
// At this point we have information about the error
HttpContext exp = HttpContext.Current;

Exception exception = exp.Server.GetLastError ();

string displayError =
"<br>Offending URL: " + exp.Request.Url.ToString () +
"<br>Source: " + exception.Source +
"<br>Message: " + exception.Message +
"<br>Stack trace: " + exception.StackTrace;

exp.Response.Write (displayError);

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

public void Dispose () {}
}
}

The Init method is where you wire events exposed by HttpApplication. Wait, is it the same HttpApplication we talked about before? Yes, it is. You've already learned how to add handlers for various evens to Global.asax. What you do here is essentially the same. Personally, I think writing an HttpModule to trap errors is a much more elegant solution than customizing your Global.asax file. Again, if you comment out the line with Server.ClearError() the exception will travel back up the stack and—provided your web.config is properly configured—a custom error page will be served.

To plug our HttpModule into the pipeline we need to add a few lines to web.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<httpModules>
<add type="AspNetResources.CustomErrors.MyErrorModule, CustomErrors" name="MyErrorModule" />
</httpModules>
</system.web>
</configuration>
Tags: , ,
Hot on Web:


About author