Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / ASP

Getting the last error in a custom error page

4.33/5 (3 votes)
5 Jan 2011CPOL 29.3K  
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
"C#"
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:
XML
<customErrors defaultRedirect="~/Whoops.aspx" mode="On"/>

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

Then GetLastError will work fine.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)