HttpModule: How to handle HttpApplication errors without HttpContext?

4

I've been finding a particularly interesting situation. I have a generic error handling routine implemented within a HttpModule , and recently I noticed a strange behavior: The HttpApplication.Error event is triggered, but HttpContext.Current is null .

This is the relevant part of HttpModule:

public void Init(HttpApplication context)
{
    context.Error += context_Error;
    context.PostMapRequestHandler += context_PostMapRequestHandler;

}

void context_PostMapRequestHandler(object sender, EventArgs e)
{
    var aux = HttpContext.Current.Handler as Page;
    if (aux != null) aux.Error += context_Error;
}

void context_Error(object sender, EventArgs e)
{
    _localLog.Add("HttpApplication error handler reached.");
    try
    {
        if (HttpContext.Current == null)
        {
            _localLog.Add("No HttpContext.");
        }
        else
        {
            var objError = HttpContext.Current.Server.GetLastError();

            if (objError == null)
            {
                _localLog.Add("GetLastError(): no error.");
                return;
            }

            //[Proper error handler follows here...]
        }
    }
}

And the event appears as follows:

Onepossibilityisthatexceptionisbeinggeneratedinanthreadoutofcontext.

Anyway,howcanIinterceptthiserrorinordertotreatit?

Crosspost: link

    
asked by anonymous 24.09.2014 / 19:52

1 answer

0

In the context_Error method you can cast the sender parameter to HttpApplication and then access the Context property. It may also happen that this is an exception that occurs without any HTTP request, for example, web application initialization / warmup code.

    
13.01.2015 / 13:43