Saturday, July 12, 2008

Error management on ASP.Net pages

How are managed errors ASP.Net pages?

A way is to modify the event "onError", in Global.asax, and make a server transfer to errors-management pages, tipically for error 500 and error 404.
We can also insert here the code to send a mail in case of error.

But the best thing is to create an HttpModule to intercept error events:

C#
public class ErrorModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.Error += new System.EventHandler(context_Error);
    }

    private void context_Error(object sender, System.EventArgs e)
    {
        Exception exception = HttpContext.Current.Server.GetLastError();
    }

    public void Dispose()
    {
    ...
    }
}

VB.Net
Public Class ErrorModule
    Inherits IHttpModule

    Public Sub Init(ByVal context As HttpApplication)
        AddHandler context.Error, AddressOf Me.context_Error
    End Sub

    Private Sub context_Error(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim exception As Exception = HttpContext.Current.Server.GetLastError
    End Sub

    Public Sub Dispose()
        ...
    End Sub
End Class

and then register it in the Web.config:

<system.web>
    <httpModules>
        <add name="ErrorModule" type="ErrorModule" />
    </httpModules>
</system.web>



HttpModules are "the better ways", 'cause permit reusability and its possible to enable or disable them from Web.config without recompile.