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:

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()

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:

        <add name="ErrorModule" type="ErrorModule" />

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

1 comment:

Recipe Spooning said...

Thank yyou for sharing this