cbp
cbp

Reputation: 25628

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?

Upvotes: 5

Views: 2178

Answers (1)

Jason Evans
Jason Evans

Reputation: 29186

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...
    }        
}

Upvotes: 2

Related Questions