6

While debugging my MVC 4 application in VS2010 SP1, the Application_Error() handler was invoked but Server.GetLastError() was null.

protected void Application_Error()
{
    var exception = Server.GetLastError();
    // exception is null.  How is that possible?
}

MSDN states Application_Error is

called if an unhandled exception occurs anywhere in your ... application... You can get information about the most recent error from the GetLastError method.

The MSDN docs for Server.GetLastError() states

Return value: The previous exception that was thrown.

How can I possibly be in a state where Application_Error() was called but Server.GetLastError() returns null?

BartoszKP
  • 32,105
  • 13
  • 92
  • 123
Eric J.
  • 139,555
  • 58
  • 313
  • 529
  • I think Application_OnError is called explicitly somewhere. So it is called albeit there is no exception. May be you can search for "Application_OnError" string in whole solution and confirm that this is not called explicitly. – Narendra Jul 27 '12 at 06:59
  • @Rain: It is not called explicitly. – Eric J. Jul 27 '12 at 07:24
  • Please check this. http://stackoverflow.com/questions/343014/asp-net-custom-error-page-server-getlasterror-is-null – Narendra Jul 27 '12 at 07:36
  • @Rain: The comments to the accepted answer say that the Exception was still available in Application_Error but lost by the time the error page was shown. In my case I almost always do have the Exception available. Just once, I did not and wonder why – Eric J. Jul 27 '12 at 17:13
  • I have recently hit this and can reproduce at will. Like the OP, I enter the Application_Error method, call Server.GetLastError. In my case I serialize the exception to session and attempt to redirect to a page which will then pull the exception out and process it correctly. Somewhere after the redirect, but before arriving at the new page, the Application_Error method is called again. this time a call to Server.GetLastError yields a null. How can this be? I apparently have an error, but no exception. :( – Rory Becker Aug 02 '18 at 10:36

1 Answers1

2

Are you using custom error handling in your web.config? I believe that if the browser issues a redirect, the previous exception will be lost. Take a look at this answer and see if your situation is similar.

Community
  • 1
  • 1
Tommy
  • 38,021
  • 8
  • 85
  • 116
  • The comments to the accepted answer say that the Exception was still available in Application_Error but lost by the time the error page was shown. In my case I almost always do have the Exception available. Just once, I did not and wonder why. – Eric J. Jul 27 '12 at 17:13