Knowing when something has gone wrong

I don't know about you, but when I am looking after a website I like to know if something has gone wrong on the website, mainly so you can fix it as soon as it happens and resolve the issue before the user of the website gets feed up and goes somewhere else.

Within ASP.NET you can configure the Global.ASAX Application_Error to capture an exceptions that are happening on you web site, so why not catch the exception and then e-mail it to the administrator of the website.

The example below works well with BlogEngine, as it uses the prebuilt settings and more importantly the Async sending of emails.

void Application_Error(object sender, EventArgs e)
    {
        
            Exception objErr = Server.GetLastError().GetBaseException();
            string err = "<b>Error Caught in Application_Error event</b><hr><br>" +
                    "<br><b>Error in: </b>" + Request.Url.ToString() +
                    "<br><b>Error Message: </b>" + objErr.Message.ToString() +
                    "<br><b>Stack Trace:</b><br>" +
                              objErr.StackTrace.ToString();
 
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
 
            string from = BlogSettings.Instance.Email;
 
            mail.To.Add(BlogSettings.Instance.Email);
            mail.From = new System.Net.Mail.MailAddress(from, from);
 
            mail.Subject = String.Format("Error in the Site - {0} Error", BlogSettings.Instance.Name);
 
            mail.Body += String.Format("{0}<br/><br/><a href='{1}'>{1}</a><br/><br/>", System.DateTime.Now.ToString(), Request.Url.ToString());
            mail.Body += "<b>Error Caught in Application_Error event</b><hr><br>" +
                          "<br><b>Error in: </b>" + Request.Url.ToString() +
                          "<br><b>Error Message: </b>" + objErr.Message.ToString() +
                          "<br><b>Stack Trace:</b><br>" + objErr.StackTrace.ToString();
            mail.Body += "Server Variables<br/><br/>";
 
            foreach (string x in Request.ServerVariables)
            {
                mail.Body += x + " - " + Request.ServerVariables[x] + "<br/>";
            }
 
            Utils.SendMailMessageAsync(mail);
    }