Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception logging HttpModule doesn't catch errors from ASP .NET Page Method

We have an HttpModule that is designed to catch exceptions and log them to the db. It looks something like this:

public class ExceptionLoggingModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.Error += OnError;
    }

    private static void OnError(object sender, EventArgs e)
    {
        try
        {
            var context = (HttpApplication) sender;
            var exception = context.Server.GetLastError();

            if (exception != null)
            {
                // Log exception
            }
        }
        catch(Exception)
        {
        }
    }
}

This works in general, but I've just noticed that the OnError method never fires when an error occurs within Page Methods (i.e. methods in a code behind file marked with the WebMethod attribute).

How come?

Is there something I can do about this, other than reimplementing the exception logging inside the Page Method itself?

like image 314
cbp Avatar asked Nov 04 '22 13:11

cbp


1 Answers

I found a solution that worked for me here:

http://blogs.microsoft.co.il/blogs/oshvartz/archive/2008/05/17/asp-net-error-handling-using-httpmodule-full-and-partial-post-back-ajax-updatepanel.aspx

Here's the key points of the handler I've written:

public class PathfinderModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PostMapRequestHandler += this.OnPostMapRequestHandler;
        context.Error += OnError;
    }

    private void OnPostMapRequestHandler(object sender, EventArgs e)
    {
        Page aux = HttpContext.Current.Handler as Page;

        if (aux != null)
        {
            aux.Error += this.OnPageError;
        }
    }

    private static void OnError(object sender, EventArgs e)
    {
        // Blah..
    }

    private void OnPageError(object sender, EventArgs e)
    {
        // Blah...
    }        
}
like image 121
Jason Evans Avatar answered Nov 08 '22 06:11

Jason Evans