Today I found myself looking at a strage situation. In our asp.net website we have a mecanism in place for unhandled application exception (yea, all good applications have an unhandled exception or two ;)), like so:
<customErrors mode="On" defaultRedirect="~/Pages/Error/Error.aspx">
<error statusCode="404" redirect="~/Pages/Error/PageNotFound.aspx"/>
</customErrors>
Then there is some code in global.asax's Application_Error, which does a Server.GetLastError() and puts it on the Session, without doing a Server.ClearError() so the exception bubbles up and the asp.net infrastructure redirects the user to the error page specified by customError's defaultRedirect attribute. The error page then takes the exception out of the Session and logs it, also displaying a (somewhat) friendly user message.
And it pretty much seemed to work, except when there was an unhandled exception in the login page (that is, the one specified in FormsAuthentication's loginUrl), which seemed to get put on the Session in global.asax, but couldn't be retrieved in the Error page, because...tada... the Session's item count was 0. Somehow, it seemed the Session would just get emptied, somewhere between global.asax's Application_Error and the Error page. After some poking around that rendered no clues or leads, I googled a bit and found this article. It seems that the asp.net infrastructure clears the Session, should an unhandled exception occur which is not “cleared” in Application_Error. Pretty useless if you ask me (also the article author's oppinion). The workaround is to clear the error and redirect to the error page “by hand”, but that defeats the purpose of the whole custom errors mechanism, like so:
Session[“exception”] = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/Pages/Error/Error.aspx");
Still, I find it strange that for any unhandled exceptions that occur in places other than the Login page, the Session is not cleared and the Error page can read the unhandled exception from the Session just fine. But if an unhandled exception occurs on the Login page, the Session magically goes away.
I'd appreciate any thoughts on the matter, while it is pending further investigation...