views:

504

answers:

1

I have an application hosted on IIS7 running in Integrated mode. I'm handling errors by putting the following into Web.config:

<httpErrors errorMode="DetailedLocalOnly" existingResponse="Replace" 
            defaultResponseMode="ExecuteURL" defaultPath="/Error.aspx">
  <remove statusCode="500" />
  <error statusCode="500" path="/Error.aspx" responseMode="ExecuteURL" />
</httpErrors>

(Because this is Integrated mode the <customErrors> block is not used.)

I want to automatically send emails every time an exception is generated. But the problem is that within Error.aspx I can't figure out how to get a reference to the exception. I tried this:

Dim oEx As Exception = Server.GetLastError()

But it returns Nothing. I also tried HttpContext.Current.Error() and HttpContext.Current.AllErrors and those don't work either.

In a custom error page running under IIS7 Integrated mode, how do I get a reference to the handled exception?

A: 

You need to intercept the error, either in Global.asax or a custom IHttpModule implementation as follows:

public class UnhandledExceptionHandlerModule : IHttpModule {
    private HttpApplication application;

    public void Init(HttpApplication application)
    {
        this.application = httpApplication;
        this.application.Error += Application_Error;
    }

    public void Dispose()
    {
        application = null;
    }

    protected internal void Application_Error(object sender, EventArgs e)
    {
        application.Transfer("~/Error.aspx");
    }
}

Then, in Error.aspx.cs:

protected void Page_Load(object sender, EventArgs e) {
    Response.StatusCode = 500;

    // Prevent IIS from discarding our response if
    // <system.webServer>/<httpErrors> is configured.
    Response.TrySkipIisCustomErrors = true;

    // Send error in email
    SendEmail(Server.GetLastError());

    // Prevent ASP.NET from redirecting if
    // <system.web>/<customErrors> is configured.
    Server.ClearError();
}
Chris Eldredge