Easiest way of global error handling in an ASP.NET application

Since there are different ways of global error handling in ASP.NET applications and you have to implement the one that best fits into your project’s architecture, I will not be discussing all the possibilities that ASP.NET provides you. However, I will just share a small code snippet that you can use to catch unhandled exceptions and write a small piece of code to send you an email whenever an error occurs. Just put the following code in your project’s Global.asax file and it is supposed to work in case you have your SMTP server settings set correctly in the web.config file or you should modify the email sending part depending on your SMTP configuration. Hope it is going to be useful for you.

void Application_Error(object sender, EventArgs e) 
{
    Exception ex = Server.GetLastError();

    if (ex != null)
    {
        if (ex.InnerException != null)
        {
            ex = ex.InnerException;
        }

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendLine("EXCEPTION - BEGIN<br/><br/>");
        sb.AppendFormat("URL: {0}<br/>", Request.Url);
        sb.AppendFormat("Time: {0}<br/><br/>", DateTime.Now);
        sb.AppendLine("EXCEPTION DETAILS:<br/><br/>");
        sb.Append(ex);
        sb.Append("<br/><br/>EXCEPTION - END");
        sb.Replace("\n", "<br/>");

        try
        {
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

            mail.To.Add("[email protected]");
            mail.Body = sb.ToString();
            mail.BodyEncoding = Encoding.UTF8;
            mail.IsBodyHtml = true;
            mail.Subject = "Exception occured at sunali.com";
            mail.SubjectEncoding = Encoding.UTF8;

            smtp.Send(mail);
        }
        catch { }
    }
}

You may also like...

2 Responses

  1. Martin Kulov says:

    Just remember that if GetLastError returns null this means that someone else already cleared the erorr. So one should also check Context.AllErrors as described here: http://sunali.com/2008/01/16/why-does-server-getlasterror-return-null/ .

  1. Wed, 4 Feb 2009

    […] genel hatayı yakalamak için Coşkun Sunalı’nın şu blog girdisine göz atmakta fayda var : Easiest way of global error handling in an ASP.NET application […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.