How do I Handle Errors and Send an Error Notification from ASP.NET Applications?

How do I set up my ASP.NET Web application to notify me with the details of an error when one occurs on my Web site? And how do I give the user a friendly message telling them an error has occurred?
When a catastrophic error occurs on your web application, the last thing you want your users to see is a big nasty error summary with stack traces and other gobbledygook that is meaningless to them. Here's a simple way to provide a "friendly" error message, while setting up e-mail notification so you can get the nitty-gritty of the error when it occurs.

  1. First you need to turn on custom errors in your Web.Config file and provide the page that will be shown when a status code 500 error occurs:

    <customErrors mode="On">
      <error statusCode="500" redirect="/InternalError.htm"/>
    </customErrors>
  2. Next, modify the Global class to wire into the Application_Error event. To make this work, add the following code to the Application_Error method in the Code Behind of your Global.asax page:

    protected void Application_Error(Object sender, EventArgs e)
    {
      StringBuilder ErrorMessage = new StringBuilder();
      Exception myError = null;
    
      myError = Server.GetLastError();
    
      if (myError != null)
      {
        while (myError.InnerException != null)
        {
          // Assign the next InnerException
          // to drill down to the lowest level exception
          myError = myError.InnerException;
        }
    
        ErrorMessage.Append("Message\r\n" + 
          myError.Message.ToString() + "\r\n\r\n");
        ErrorMessage.Append("Source\r\n" + 
          myError.Source + "\r\n\r\n");
        ErrorMessage.Append("Target site\r\n" + 
          myError.TargetSite.ToString() + "\r\n\r\n");
        ErrorMessage.Append("Stack trace\r\n" + 
          myError.StackTrace + "\r\n\r\n");
        ErrorMessage.Append("ToString()\r\n" + 
          myError.ToString() + "\r\n\r\n");
    
        MailMessage objMail = new MailMessage();
        objMail.To = "You@YourISP.com";
        objMail.From = "YourSite@YourISP.Com";
        objMail.Subject = "Error 500 in: " + Request.Url.ToString() 
          + " at " + DateTime.Now.ToString();
        objMail.BodyFormat = MailFormat.Text;
        objMail.Body = ErrorMessage.ToString();
        SmtpMail.SmtpServer = "YourMailServer";
        SmtpMail.Send(objMail);
      }
    }
Note the use of the loop in the code above. This is an important piece because if you just access Server.GetLastError() you most likely will not get anything useful. When an ASP.net exception occurs, Server.GetLastError().Message will return this: System.Web.HttpUnhandledException. This is the top level exception that the Http runtime is throwing, but unfortunately it doesn't contain anything that pertains to what actually tripped up the code. So we need to drill down to the inner-most exception by recursively checking myError.InnerException for a non-null condition.
while (myError.InnerException != null)
{
  // Assign the next InnerException
  // to drill down to the lowest level exception
  myError = myError.InnerException;
}

Instead of looping through the exceptions, you can also call GetBaseException() to get at the inner most exception directly:

myError = Server.GetLastError().GetBaseException();
	
myErrorMessage += "Message\r\n" +
	myError.Message.ToString() + "\r\n\r\n";
myErrorMessage += "Source\r\n" +
	myError.Source + "\r\n\r\n";
myErrorMessage += "Target site\r\n" +
	myError.TargetSite.ToString() + "\r\n\r\n";
myErrorMessage += "Stack trace\r\n" +
	myError.StackTrace + "\r\n\r\n";
myErrorMessage += "ToString()\r\n\r\n" +
	myError.ToString();

For all this code to work, you'll need to import the following two namespaces in your Global class:

using System.Text;
using System.Web.Mail;
System.Text is necessary for the StringBuilder class, while obviously you'll need System.Web.Mail to send the e-mail.

Now, whenever an error occurs, your users will only see the error page you specified in the Web.Config file. Whatever you put in that page is entirely up to you. Be sure you provide a link back to your homepage or another useful location, so your user can quickly resume browsing your site. As soon as the error occurred, you'll receive an e-mail with all the details of the error, including the date and time it occurred, the name of the offending page, and detailed information about the actual error.

For a more detailed look at error handling and logging, take a look at Logging Errors to the Event Log in ASP.NET Applications.

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Tuesday, May 23, 2006 9:03:27 PM Bent Rasmussen said:
A very good. clear and useful article

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.