ASP.NET Tip: Application Error Event Handler Implementation
This is a small example of Application Error Event Handler implementation in ASP.NET 2.0 (global.asax), which sends formatted exception message to administrator using SmtpClient. Please notice various HTTP headers that are essential metadata together with actual exception message.
protected void Application_Error(Object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder(400);
sb.Append("Application Error\n\n");
// Get user IP
sb.Append("User IP :");
sb.Append(Request.UserHostAddress);
// Get the path of the page
sb.Append("\n\nError in Path :");
sb.Append(Request.Path);
// Get the QueryString along with the Virtual Path
sb.Append("\n\nError Raw Url :");
sb.Append(Request.RawUrl);
// Create an Exception object from the Last error
// that occurred on the server
Exception myError = Server.GetLastError();
// Get the error message
sb.Append("\n\nError Message :");
sb.Append(myError.Message);
// Source of the message
sb.Append("\n\nError Source :");
sb.Append(myError.Source);
// Stack Trace of the error
sb.Append("\n\nError Stack Trace :");
sb.Append(myError.StackTrace);
// inner exception
if (myError.InnerException != null)
{
sb.Append("\n\nInner exception : ");
sb.Append(myError.InnerException);
}
// Method where the error occurred
sb.Append("\n\nError TargetSite :");
sb.Append(myError.TargetSite);
// Email Exception
SmtpClient smtpClnt = new SmtpClient();
MailMessage em = new MailMessage("admin@mysite.com", "admin@mysite.com");
em.Subject = String.Format("MySite: Application Error. ({0})",
Request.UserHostAddress);
em.Body = sb.ToString();
smtpClnt.Send(em);
}
SmtpClient settings should be pre-configured in web.config like so:
< system.net>
< mailSettings>
< smtp from="admin@mysite.com">
< network host="localhost" port="25" />
< /smtp>
< /mailSettings>
< /system.net>
When exception message is send to administrator, the user should see custom error page that is pre-configured in web.config like so:
< customErrors mode="On">
< error statusCode="500" redirect="~/Pages/Errors/Error500.aspx" />
< /customErrors>
Saturday, December 23, 2006 8:45 AM