Reader Level:
ARTICLE

Error handler for web applications

Posted by Michael Livshitz Articles | Visual C# May 15, 2007
In this article I will describe the error handler for ASP.NET 2.0 applications, that is developed in a separate class library project . You can use it in any web application you want by adding a reference to the compiled dll assembly without writing many lines of code. The examples are written using C#.
  • 0
  • 0
  • 9362

After deploying your web application you have to know about errors that occur when somebody (any "user") uses the application. Usually, you need to know real situation (real error message, source etc.) and to send to the client only some short message. One of convenient methods to make it is to mail to you the real error message and to redirect the user (client) to some special error page. In this article I will describe the error handler for ASP.NET 2 applications that is developed in a separate class library project. You can use it in any web application you want by adding a reference to the compiled dll assembly without writing many lines of code. The examples are written using C#.

In the project, named ErrorHandler and having type of the "Class Library", we create the class WebErrorHandler. Among other properties of the class there are such properties as: C_MailAddressTo, which set or get all emails where the error message has to be sent to (your email, email of your manager, email of the manager of your manager etc.); C_MailSubject, which set or get the subject of the mail with default value "Error Message"; C_Host, which set or get the domain name; C_RedirectPath, which set or get the URL of the web page for the error messages. The class has the method doErrorHandler(), which forms the error message, sends this message according to the C_MailAddressTo property and redirects the user to the special error page (according to the C_RedirectPath property).

The
C_RedirectPath property has one small feature. If the string (C_RedirectPath)  contains "?" (for example:"ErrorForm.aspx?ErrorMessage="),  we have possibility to receive the "short error message" on our error page. Saying "short error message", I just mean the first sentense of the whole error message. It can be very useful when we want not only to inform about some error (like: "
An error has occurred!"), but to add some information about the kind of the error.

For example, suppose we have the message :

"
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: " and so on.)

In this case the "short error message" is: "
An error has occurred while establishing a connection to the server".

The code of the WebErrorHandler class is the following:

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Net.Mail;

using System.Web;

using System.Web.UI;  

 

namespace ErrorHandler

{

    public class WebErrorHandler

    {

        #region "forClass"

        private List<string> _MailAddressTo;

        private string _MailSubject = "Error Message";

        private string _MailAddressFrom = "";

        private string _RedirectPath = "ErrorHandler.aspx";

        private string _Host="";

        private HttpResponse _Response;

        private HttpServerUtility _Server;

 

        #endregion

 

        #region "Properties"

        public List<string>  C_MailAddressTo

        {

            get { return _MailAddressTo; }

            set { _MailAddressTo = value; }

        }

 

        public string  C_MailSubject

        {

            get { return _MailSubject; }

            set { _MailSubject= value; }

        }

 

        public string C_MailAddressFrom

        {

            get { return _MailAddressFrom; }

            set { _MailAddressFrom = value; }

        }

 

        public string C_RedirectPath

        {

            get { return _RedirectPath; }

            set { _RedirectPath = value; }

        }

 

        public string  C_Host

        {

            get { return _Host; }

            set { _Host = value; }

        }

 

        public HttpResponse  C_Response

        {

            set { _Response = value; }

        }

        public HttpServerUtility C_Server

        {

            set { _Server = value; }

        }

        #endregion

 

        public void doErrorHandler()

        {

            Exception exc = _Server.GetLastError().GetBaseException();

            string sErrorMessage =

                  "<br/><b style ='color:Red'>MESSAGE:</b><br/>" +

                  exc.Message +

                  "<br/><b style ='color:Red'>SOURCE:</b><br/>" +

                  exc.Source +

                  "<br/><b style ='color:Red'>TARGETSITE:</b><br/>" +

                  exc.TargetSite +

                  "<br/><b style ='color:Red'>StackTrace:</b><br/>" +

                  exc.StackTrace +

                  "<br/><b style ='color:Red'>Data:</b><br/>" +

                  exc.Data +

                  "<br/><b style ='color:Red'>InnerException:</b><br/>"

                  + exc.InnerException;

            string sErrorMessageShort =

                exc.Message.Substring(0, exc.Message.IndexOf("."));

            MailMessage messageMail = new MailMessage();

            SmtpClient clientMail = new SmtpClient();

 

            if (_MailAddressFrom.Trim() != "")

            {

                messageMail.From = new MailAddress(_MailAddressFrom);

            }

            foreach (string  addressTo in _MailAddressTo )

            {

                messageMail.To.Add(new MailAddress(addressTo));   

            }

            messageMail.Subject = _MailSubject;

            messageMail.Body = sErrorMessage;

            messageMail.IsBodyHtml = true;

 

            if (_Host.Trim() != "")

            {

                clientMail.Host = _Host;

            }

            clientMail.Send(messageMail);

            if (_RedirectPath.Contains("?"))

            {

                _Response.Redirect(_RedirectPath + sErrorMessageShort);

            }

            else

            {

                _Response.Redirect(_RedirectPath);

            }

            _Server.ClearError();

        }

    }

}

After building our project you can use it in any web application you want by adding a reference to the compiled ErrorHandler.dll assembly. In order to handle error we will use the Application_Error method of the Global.asax file:

 

void Application_Error(object sender, EventArgs e)

{

    ErrorHandler.WebErrorHandler ErrHandler =

        new ErrorHandler.WebErrorHandler();

    List<string> MailTo = new List<string>();

 

    MailTo.Add("My_Email@email");

    MailTo.Add("MyManager_Email@email");

    MailTo.Add("MyManagerManager_Email@email");

    ErrHandler.C_Host = "MyHost";//or from Web.Config

    ErrHandler.C_MailAddressFrom =

        "fromError@mail";//or from Web.Config

    ErrHandler.C_MailAddressTo = MailTo;

    ErrHandler.C_MailSubject =

        "One more Error Message";//or used default

    //ErrHandler.C_RedirectPath =

    //    "~/Forms/ErrorForm.aspx";//without message

    ErrHandler.C_RedirectPath =

        "~/Forms/ErrorForm.aspx?ErrorMessage=";

    ErrHandler.C_Response = Response;

    ErrHandler.C_Server = Server;

    ErrHandler.doErrorHandler();

}

If you want to define the "Host" and  "Mail from" in the Web.Config file you do not need to set the properties C_Host and C_MailAddressFrom in the Application_Error method, you just have to add inside of the "configuration" tag of  the Web.Config the following code:

 

<system.net>

  <mailSettings>

    <smtp from="fromError@mail">

      <network host="MyHost"/>

    </smtp>

  </mailSettings>

</system.net>

In order to test our ErrorHandler, just add to your project some ErrorPage.aspx with at least one label (for example: LabelErrorMessage). Add to Page_Load method the following code:

 

protected void Page_Load(object sender, EventArgs e)

{

    if (Request.QueryString["ErrorMessage"] != null

        && Request.QueryString["ErrorMessage"].Trim ()!="")

    {

        LabelErrorMessage.Text = Request.QueryString["ErrorMessage"];  

    }

}

 

Now "spoil" your connection string and run the application. You (your manager, etc.) will receive the email like this (Fig. 1):



Figure 1.

The user will be redirect to the ErrorPage like this (fig.2):



Figure 2.

CONCLUSION

I hope, that this article will help you to create your own ErrorHandler.dll with your own requirements, which can help to standardize and develop your web application.

Good luck in programming ! 
 

COMMENT USING

Trending up