How do I setup a global exception handler for my application?
From Guidance Share
J.D. Meier, Prashant Bansode, Alex Mackman
Answer
To set up a global exception handler for your application, write your exception handling code in the Application_Error event handler that is implemented in Gloabal.asax. This event is raised when exceptions are allowed to propagate from page-level error handlers or if there is no page error handler. Ideally, the exception handling code you write in the Application_Error method will collect and log as much exception details necessary for you to diagnose the error. An unhandled exception might leave your application in an unstable and un-usable form, hence as a fall back mechanism you should always implement a global exception handler. A sample global exception handler that writes exception details to the event log is shown below:
<%@ Application Language="C#" %> <%@ Import Namespace="System.Diagnostics" %>
<script language="C#" runat="server">
void Application_Error(object sender, EventArgs e)
{
//get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();
//log the details of the exception and page state to the
//Event Log
EventLog.WriteEntry("My Web Application",
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
EventLogEntryType.Error);
//Optional email or other notification here... } </script>
