I have a custom error page set up for my application:
<customErrors mode="On" defaultRedirect="~/errors/GeneralError.aspx"
/>
In Global.asax, Application_Error(), the following code works to get the exception details:
Exception ex = Server.GetLastError();
if (ex != null)
{
if (ex.GetBaseException() != null)
ex = ex.GetBaseException();
}
By the time I get to my error page (~/errors/GeneralError.aspx.cs), Server.GetLastError() is null
Is there any way I can get the exception details on the Error Page, rather than in Global.asax.cs ?
ASP.NET 3.5 on Vista/IIS7
OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx
with this very illustrative diagram:
diagram http://i.msdn.microsoft.com/Aa479319.customerrors_01(en-us,MSDN.10).gif
in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.
it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.
Try using something like
Server.Transfer("~/ErrorPage.aspx");
from within theApplication_Error()
method of global.asax.csThen from within
Page_Load()
of ErrorPage.aspx.cs you should be okay to do something like:Exception exception = Server.GetLastError().GetBaseException();
Server.Transfer()
seems to keep the exception hanging around.Whilst there are several good answers here, I must point out that it is not good practice to display system exception messages on error pages (which is what I am assuming you want to do). You may inadvertently reveal things you do not wish to do so to malicious users. For example Sql Server exception messages are very verbose and can give the user name, password and schema information of the database when an error occurs. That information should not be displayed to an end user.
Here is my solution..
In Global.aspx:
In Oops.aspx: