Click here to Skip to main content
15,884,353 members
Articles / Programming Languages / ASP
Tip/Trick

Getting the last error in a custom error page

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
5 Jan 2011CPOL 28.4K   3   4
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)


Written By
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

Comments and Discussions

 
GeneralReason for my vote of 3 ghfhfh hgf hjgkj kj kh kjhkj k Pin
mohsen Penhani10-Jan-11 10:35
mohsen Penhani10-Jan-11 10:35 
GeneralThat is entirely up to you: I don't know what you are using ... Pin
OriginalGriff10-Jan-11 3:23
mveOriginalGriff10-Jan-11 3:23 
Generalwhat code is ErrorLog ?? Pin
kiquenet.com10-Jan-11 3:20
professionalkiquenet.com10-Jan-11 3:20 
GeneralHi Pin
premchand197524-May-11 2:58
premchand197524-May-11 2:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.