title: Using IHttpModule Over Global.asax
body: <p>I've been given the thrilling task of re-writing our exception handling system.  Whilst I will state that handling exceptions from an application-wide point of view isn't something we want, typically it's unavoidable when our team are understaffed for the sheer amount of work we need to push out the door, so please, no flaming the globalised solution to exception handling here :)</p>
  
  <p>I've had a good hunt to see what common solutions exist.  At the moment we use Global.asax with the Application_Error event to do Server.GetLastError() which is placed in Session state then a redirect is called to another page where the session data is then retrieved and output in a human readable format.  The redirect also calls a sproc which will carefully audit the error information which is a) e-mailed to the developers and b) viewed from a web page only viewable by developers.</p>
  
  <p>The new way I've seen of doing things is using the IHttpModule interface using a class in App_Code to do something along these lines (this is my quick implementation)</p>
  
  <pre><code>Imports Microsoft.VisualBasic
  
  Public Class ErrorModule : Implements IHttpModule
  
    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
      ' Not used
    End Sub
  
    Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
      AddHandler context.Error, AddressOf context_Error
    End Sub
  
    Public Sub context_Error(ByVal sender As Object, ByVal e As EventArgs)
      Dim ex As Exception = HttpContext.Current.Server.GetLastError
  
      ' do something with the error
      ' call the stored procedure
      ' redirect the user to the error page
  
      HttpContext.Current.Server.ClearError()
      HttpContext.Current.Response.Redirect("index.htm")
  
    End Sub
  End Class
  </code></pre>
  
  <p>My question is, what is the benefit of this solution over using Global.asax events?  Additionally, what is the best way to hand the data to an error page?</p>
  
  <p><em>EDIT:</em> The code above does work by the way ;)</p>
  
  <p><strong>EDIT:</strong> Also, how does the HttpModule work behind the scenes?  Does it just register the Error event to that particular function on application start?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Upon much further investigation it seems grabbing session data is really, really messy when it comes to using IHttpModule interface.  I don't think MS have matured HttpModule enough for it to be used in our particular scenario - until there are events specific to session data it's too dangerous for us to use.</p>