65.9K
CodeProject is changing. Read more.
Home

Getting the last error in a custom error page

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3 votes)

Jan 3, 2011

CPOL
viewsIcon

29300

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