Global.asax, is the global file in the web application, which offers application level events to be registered. There are many of the events in this file which can be used for specific purposes. "Application_Error" is the one which is fired when some unhandled exception occurs in the application. It is very significant in this basic way that if that unhandled exception is not handled in this event then the exception summary page will be shows to the user of the application. Which would perplex him, leaving him uncertain about the application. So, it's always good to handle unhandled exceptions in this event.
This article would focus not only on handling the exception in the "Application_Error" event, but also to log the exception detail in the "Event Viewer".
public class Global : System.Web.HttpApplication
{
protected void Application_Error(object sender, EventArgs e)
{
try
{
// gets the error occured
Exception ex = Server.GetLastError().GetBaseException();
// checks if the event source is registered
if (!System.Diagnostics.EventLog.SourceExists(".NET Runtime"))
{
System.Diagnostics.EventLog.CreateEventSource(".NET Runtime", "Application");
}
//log the details of the error occured
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = ".NET Runtime";
log.WriteEntry(String.Format("\r\n\r\nApplication Error\r\n\r\n" +
"MESSAGE: {0}\r\n" +
"SOURCE: {1}\r\n" +
"FORM: {2}\r\n" +
"QUERYSTRING: {3}\r\n" +
"TARGETSITE: {4}\r\n" +
"STACKTRACE: {5}\r\n",
ex.Message,
ex.Source,
Request.Form.ToString(),
Request.QueryString.ToString(),
ex.TargetSite,
ex.StackTrace),
System.Diagnostics.EventLogEntryType.Error);
Server.ClearError();
}
catch
{
// in case of exception occured in log
Server.ClearError();
}
}
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
The code in the "Application_Error" event, first retrieves the currently occurred exception from server object, to write its details in the Event Viewer Log. "System.Diagnostics.EventLog" makes it possible to write the log details in the Event Viewer. It creates the event source, for writing the event messages in case the source does not exist already, and then using the object of EventLog, it writes the formatted detail message in the event viewer. "Server.ClearError()" clears the previously occurred exception.