Handling all errors within an asp.net application.
Posted by Sem Dendoncker on September 5th, 2010Hello,
This post will describe how you can catch all errors in an asp.net application, process the error and finally show a nice page telling the users there was an error and the developers were informed about the issue.
For starters your application needs a Global.asax file.
To do this you just right click the website –> add new Item –> Global application class and press Add.
You will see some predefined methods in this file. We are interested in the “Application_Error” method.
This method is always executed after an error occurred.
Here’s the code you need to see the error, handle it and negate the error for the user.
void Application_Error(object sender, EventArgs e)
{
StringBuilder message = new StringBuilder();
if (Request != null)
{
message.AppendFormat("Error url: ", Request.Path);
}
if (Server != null)
{
Exception ex;
for (ex = Server.GetLastError(); ex != null; ex = ex.InnerException)
{
// add everthing you want from the exception to the message.
message.Append(String.Format("Exception: {0}", ex.InnerException));
message.Append(String.Format("Stacktrace: {0}", ex.StackTrace));
}
}
// You can retrieve any information as you would in a page.
// Ex: Session data, Cookie Data, etc ...
// All this data can be added to the message.
// Mail the message to the developers (this way they now something went wrong)
// This is just an example of a custom made service for bug reporting.
BugReportingService service = new BugReportingService();
service.Message = message.ToString();
service.ReportToDevelopers();
// This will clear the error (this way the users will not see the error).
Server.ClearError();
// Finally redirect the user to a custom made (user friendly) error page.
Response.Redirect("~/FriendlyErrorPage.aspx");
}
That’s all there is to it.
Off course the above is just an example you can modify it in so many different ways I could write 20 pages about it.
Cheers,
Sem
Recent Comments