Getting the last error in a custom error page

When you provide a custom error handler page, it is useful to be able to log what caused the problem, so that you can fix it. Server.GetLastError() will not return anything in the page, though…

When you provide a custom error handler page, it is useful to be able to log what caused the problem, so that you can fix it.
Normally, this is just a case of using

Collapse
        Exception lastError = Server.GetLastError();
        if (lastError == null)
            {
            ErrorLog("An error occurred, but no error information is available");
            }
        else
            {
            ErrorLog(lastError.ToString());
            }

This fails however, because the redirect to the error page loses the error information.
You can handle a Page Error event and pass the error through in a session variable, but that is a bit clunky, and means coding in your Master page and / or each actual page, plus the session variable itself.
Alternatively, there is a redirect mode as part of the custom error setup which redirects without re-loading. This preserves error information.
Change your customErrors declaration from:

    <customErrors defaultRedirect="~/Whoops.aspx" mode="On"/>

To

    <customErrors defaultRedirect="~/Whoops.aspx" mode="On" redirectMode="ResponseRewrite"/>

Then GetLastError will work fine.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: