Automatic Error Reports Sent Via Email

3/18/2008

This update is pretty small in scope but it's a trick that has helped me out numerous times. Here's the basic premise, your website is having an error of some sort. Some bug that you had no idea about crops up and is causing errors to pop up for a large number of visitors. How can I find out about it without visiting my website constantly or waiting for someone to email me concerning it? Simply use the Application_Error function of the global.asax file to send you the errors when they occur.

It's actually very easy to do and in fact here is the code to accomplish it:

   1: protected void Application_Error(object sender, EventArgs e)
   2: {
   3:     string ErrorDescription = "Server : " + System.Environment.MachineName + "\n\n"; 
   4:     ErrorDescription += "Request.Path : " + Request.Path + "\n\n"; 
   5:     System.Exception error = Server.GetLastError(); 
   6:     EmailError(
   7:         youremailaddress@website.com, //to
   8:         youremailaddress@website.com, //from
   9:         "Application Error : "+Server.MachineName, //subject
  10:         ErrorDescription + error.ToString(), //body,
  11:         "youremailserver", //Mail Server
  12:         25 //25 is the default port for email, change if necessary
  13:     );
  14: } 
  15:  
  16: private void EmailError(string to,string from,string subject,
  17:     string body,string mailServerHost,int mailServerPort)
  18: {
  19:     try
  20:     {
  21:         System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage();
  22:         MailMessage.Priority = System.Net.Mail.MailPriority.High;
  23:         MailMessage.To.Add(to);
  24:         MailMessage.From = new System.Net.Mail.MailAddress(from);
  25:         MailMessage.Subject = subject;
  26:         MailMessage.Body = body;
  27:         System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(mailServerHost, mailServerPort);
  28:         smtpClient.Send(MailMessage);
  29:     }
  30:     catch
  31:     {
  32:     }
  33: }

That's all there is to it. Really nothing to it. So try it out, leave feedback, and happy coding.



Comments