I am trying to write a global custom error page. I thought I would jot down
some of what I've learned so far...
At first I just used the default customErrors section with a defaultRedirect
tag, as such:
<customErrors defaultRedirect ="error.aspx " mode="On" />
First thing I found out about this method, is that I didn't have access to
the exception object in my error.aspx page. So this page was going to be
very uninformitive. It appears that the Server.GetLastE rror cannot be
called outside of the Application_Err or event in the global.asax file.
I found this asp.netPRO example that I am now using as a starting point:
http://www.aspnetpro.com/features/20...200305dk_f.asp
In the article the author saves the Exception in a "global" module variable
(how strange) so that he could use it later in his custom error page. This
worked Ok, but this doesn't appear to be thread-safe. So I quickly decided
I should be using a Session variable instead. The author hints that there
are other methods of doing this, but wisely avoids the whole issue. :)
Lots of examples on Google of people trying to stuff their Exception into a
Session("LastEr ror") in the Application_Err or event. Just as many people
wondering why it isn't working. ;(
Turns out you can write to the Session object in the Application_Err or
event, but it won't save it unless you also do a Server.ClearErr or. Ouch!
Take a look http://tinyurl.com/r3xk for a quick explanation.
So now my Application_Err or event is looking like this:
Sub Application_Err or(ByVal sender As Object, ByVal e As EventArgs)
'Grab a reference to the last error. Use InnerException because
'ASP.NET wraps errors here in an HttpUnhandledEx ception.
Session("LastEr ror") = Server.GetLastE rror.InnerExcep tion
Server.ClearErr or() ' must clear error else session state will not
be preserved!!!
' since manually clearing error, must manually redirect...
'Server.Transfe r("~/error.aspx")
Response.Redire ct("~/error.aspx")
End Sub
I have also taken out the defaultRedirect ="error.aspx " tag in the web.config
since this will make it pointless(?)
Notice, I abandoned the server.transfer call in favor on the
response.redire ct. Every single time I try and use server.transfer the page
will ignore my style sheet(!) Anybody?
Since my app is also using forms authentication, I went back an made sure my
error page was accesible whether logged in or not...
<location path="Error.asp x">
<system.web>
<authorizatio n>
<allow users="*" />
</authorization>
</system.web>
</location>
I have seen people using this syntax in their web config: <location
path="~/Error.aspx">, but this doesn't appear to work (or even be
necessary).
Anyways, I hope this helps somebody out there.
Greg