I have an asp.net application and I am trying to handle custom exception using Application_Error. It works nicely but I have new requirement to set the error data in Session obj
I've just come across this problem myself and, after a couple of hours of messing around, managed to solve it. The issue is that Application_Error()
clears the session after executing as part of some sort of "cleanup" routine which you need to stop.
The solution I found is as follows:
Call Server.ClearError();
- this clears the last error from the application and stops the "cleanup" taking place, thus preserving session.
The (unwanted imho) side-effect of this is that it no longer performs the automatic redirect to the error page, so you need to explicitly call Response.Redirect("~/error.aspx");
So, something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect!
Response.Redirect("~/error.aspx");
}
If you don't want to hard-code the URL, you could grab the defaultRedirect
URL directly from the customerrors
section in the web.config
, which would give you something like this:
protected void Application_Error(object sender, EventArgs e)
{
// Grab the last exception
Exception ex = Server.GetLastError();
// put it in session
Session["Last_Exception"] = ex;
// clear the last error to stop .net clearing session
Server.ClearError();
// The above stops the auto-redirect - so do a redirect using the default redirect from the customErrors section of the web.config!
var customerrors = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
Response.Redirect(customerrors.DefaultRedirect);
}