ASP.NET Error Handling: Creating an extension method to send error email

Error handling in asp.net required to handle any kind of error occurred. We all are using that in one or another scenario. But some errors are there which will occur in some specific scenario in production environment in this case We can’t show our programming errors to the End user. So we are going to put a error page over there or whatever best suited as per our requirement. But as a programmer we should know that error so we can track the scenario and we can solve that error or can handle error. In this kind of situation an Error Email comes handy. Whenever any occurs in system it will going to send error in our email.

Here I am going to write a extension method which will send errors in email. From asp.net 3.5 or higher version of .NET framework  its provides a unique way to extend your classes. Here you can fine more information about extension method. So lets create extension method via implementing a static class like following. I am going to use same code for sending email via my Gmail account from here. Following is code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace Experiement { public static class MyExtension { public static void SendErrorEmail(this Exception ex) { MailMessage mailMessage = new MailMessage(new MailAddress("from@gmail.com") , new MailAddress("to@gmail.com")); mailMessage.Subject = "Exception Occured in your site"; mailMessage.IsBodyHtml = true;

        System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();

        errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>","Exception",ex.Message));
        errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", "Stack Trace", ex.StackTrace));

        if (ex.InnerException != null)
        {
            errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", " Inner Exception", ex.InnerException.Message));
            errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}<BR/>", "Inner Stack Trace", ex.InnerException.StackTrace));
        }

        mailMessage.Body = errorMessage.ToString();

        System.Net.NetworkCredential networkCredentials = new
        System.Net.NetworkCredential("youraccount@gmail.com", "password");

        SmtpClient smtpClient = new SmtpClient();
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = networkCredentials;
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
        smtpClient.Send(mailMessage);


    }
}

}

After creating an extension method let us that extension method to handle error like following in page load event of page.

using System;

namespace Experiement
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender,System.EventArgs e)
        {
            try
            {
                throw new Exception("My custom Exception");
            }
            catch (Exception ex)
            {
                ex.SendErrorEmail();
                Response.Write(ex.Message);
            }
        }

    }
}

Now in above code I have generated custom exception for example but in production It can be any Exception. And you can see I have use ex.SendErrorEmail() function in catch block to send email. That’s it.. Now it will throw exception and you will email in your email box like below.

Error Handling in ASP.NET 

That’s its. It’s so simple…Stay tuned for more.. Happy programming..

Shout it

4 Comments

  • Hi,

    I like this idea, we did this on another way - without the need for extension methods so it's available in more versions of the .net framework:

    Extend your asp.net page from an own base. e.g.:

    Normally:
    public partial class PageExample : Page
    Now:
    public partial class PageExample : MARKVTINFO.Generic.BasePage

    Then my file like this:
    namespace MARKVTINFO.Generic
    {
    public class BasePage : Page

    Nothing much so far, but in my BasePage class i can do automatic error mailing so it's easier to implement and possibly faster..

    Just add this method on the new class that is inherited:

    ///
    /// Handles the Error event of the Page control.
    ///
    /// The source of the event.

    /// The instance containing the event data.

    public void Page_Error(object sender, EventArgs e)
    {
    Exception objErr = Server.GetLastError();
    string urlError = Request.Url.ToString();
    // here would be a call to e-mail function
    // Logger.EmailLogger.Send(objErr, urlError);
    // send to generic error page if needed for the end users
    //Response.Redirect("ErrorPage.aspx");
    }

    You can put more in this inherited base page like i18n, changing language settings etc.

  • Why not to use Healthmornitoring???

  • @markvt- There are lots of way of doing that and there will be another way.

    @hjf223- On health monitoring you can have server details and exception but you will get total stack trace.


  • Did you know that you can call Exception.ToString() to get all exception details including inner exceptions?

Comments have been disabled for this content.