Click here to Skip to main content
15,861,168 members
Articles / Web Development / ASP.NET

Implementing Custom Error Handling Library for ASP.NET using XML & C#.NET

Rate me:
Please Sign up or sign in to vote.
4.38/5 (7 votes)
24 Mar 2010CPOL3 min read 45.4K   296   33   15
Handling & tracking Exceptions / Errors in ASP.NET using XML

Introduction

Being ASP.NET developers, we develop a web project and get it completed in a month's time as there are many organizations which work on very tight bound timeline for developing web sites or web application projects, and deliver the project to the client within months. After project delivery, if the client come up saying that they are facing problems or application is giving errors, at that time it always becomes a headache for a developer to test each thing, even the whole project sometimes to find small errors (by means of error here, we are not talking about logical errors, we talking about exceptions which are mostly responsible for errors in the application). There are many exceptions which .NET framework fires which we never come to find out while debugging or developing the application. Those exceptions never directly affect the application but each small exception puts unnecessary load on the server. Here is the solution to track each and every small thing happening inside your ASP.NET web application, which I named as “Custom error tracking library”.

Implementing Custom Error Handling Library

The very first question that will come up is what is the core concept for this. Concept is that we will be maintaining an XML file with a predefined structure which I have built which will contain all the required fields as nodes and subs, which we call as errorlog.xml. There will be a CS library file which will track each and every minor error/exception that happens inside the application or .NET Framework and will put the error details inside the XML file. Once we get the CS library ready with us, we will just have a simple function with 2 overload methods as per the requirement in each try/catch blocks of the code and also in Application_Error event of Global.asax file.

XML File Structure for Error Logging

XML
<xml version="1.0? encoding="utf-8?>
<errorlog>
  <error>
    <datetime>datetime</datetime>
    <filename>filename</filename>
    <classname>classname</classname>
    <methodname>methodname</methodname>
    <errormethod>errormethod</errormethod>
    <message>ErrorMessage</message>
    <errordetails>Details goes here</errordetails>
    <IP>IP address</IP>
    <url>URL</url>
  </error>
</errorlog>  

Inside the root node of the XLM file <errorlog>, there will be a sub node <error> which will get duplicated for each error. For each error, the library will generate a node with all the below listed details in the XML file. Next to the last error node. So for each error, there will be a separate ERROR node. Each field of the above XML file is described below:

  1. Datetime: Date and time of the error/exception
  2. File name: File name where exception or error happens
  3. Class name: Classname in which error occurred
  4. Method name: Function name where there is an error
  5. Error method: Name of the function which contains error code
  6. Message: Error message/exception message
  7. Error details: Detailed error description which will show the whole stack trace of the functional execution
  8. IP: Client IP address
  9. URL: Absolute error URL

Code Inside CS file (errorHandler.cs)

There will be a CS library file where we will write all the functionality for error handling and writing errors into XML file. errorHamdler.cs file will have two static methods named WriteError(). There will be two overloaded methods for the same functions with different parameters. CS file will look as given below. We name it as errorHamdler.cs.

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
namespace TheCodeCenter
{
    public class errorHandler
    {
        string _strErrorMessage, _strDetails, _strClassName, _strMethodName;
        DateTime _dtOccuranceTime = new DateTime();
        public errorHandler()
        {

        }
        public errorHandler(DateTime time, string className, 
		string methodName, string errorMessage, string details)
        {
            _dtOccuranceTime = time;
            _strClassName = className;
            _strDetails = details;
            _strErrorMessage = errorMessage;
            _strMethodName = methodName;
        }
        public static void WriteError(Exception ex)
        {
            WriteError(ex, "");
        }
        public static void WriteError(Exception ex, string fileName)
        {
            XmlDocument doc = new XmlDocument();
            string strRootPath = System.Configuration.ConfigurationManager.AppSettings
				["logfilepath"].ToString();
            string xmlPath = System.Web.HttpContext.Current.Server.MapPath(strRootPath);
            doc.Load(@xmlPath);
            XmlNode newXMLNode, oldXMLNode;
            oldXMLNode = doc.ChildNodes[1].ChildNodes[0];
            newXMLNode = oldXMLNode.CloneNode(true);

            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();

            newXMLNode.ChildNodes[0].InnerText = DateTime.Now.ToString();
            newXMLNode.ChildNodes[1].InnerText = fileName;
            newXMLNode.ChildNodes[2].InnerText = methodBase.DeclaringType.FullName;
            newXMLNode.ChildNodes[3].InnerText = methodBase.Name;
            newXMLNode.ChildNodes[4].InnerText = ex.TargetSite.Name;
            newXMLNode.ChildNodes[5].InnerText = ex.Message;
            newXMLNode.ChildNodes[6].InnerText = ex.StackTrace;
            newXMLNode.ChildNodes[7].InnerText = 
		System.Web.HttpContext.Current.Request.UserHostAddress;
            newXMLNode.ChildNodes[8].InnerText = 
		System.Web.HttpContext.Current.Request.Url.OriginalString;
            doc.ChildNodes[1].AppendChild(newXMLNode);
            doc.Save(@xmlPath);
            doc.RemoveAll();
        }
    }
}

Web.Config Settings

XML
<appSettings>
	<add key="logfilepath" value="~/errorHandling/errorlog.xml"/>
</appSettings>

How to Use Error Handler in Application

Now everything is ready to be used in a real time application. In each try/catch block, we have to call Writeerror() function as described below:

C#
protected void Page_Load(object sender, EventArgs e)
{
    throw new Exception("asds");

    try
    {
        int a = 0;
        int b = 10 / a;
        //throw new Exception("Custom error");
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        TheCodeCenter.errorHandler.WriteError(ex, "Default.aspx.vb");
    }
}

Apart from each try/catch block, we will put some code in the Global.asax file too, as given below:

C#
void Application_Error(object sender, EventArgs e)
{
    object a = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
    TheCodeCenter.errorHandler.WriteError
	(Server.GetLastError().GetBaseException(), "Global.asax");
}

The reason behind putting code in Global.asax file is very important and necessary as there might be many exceptions which occurs at the application level and cannot be traceable in any try/catch blocks in any function or events. So any error except try/catch blocks will come in this event (Application_Error) and will get inserted into XML file. That’s it, we are done with the error handling, and all errors will be traceable from the XML file which is being generated via the error handler.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Gateway Technolabs Pvt. Ltd
India India
Having 4+ years of Technical Experience in asp.net,c#.net, SQL Server 2008,AJAX, XML,JQuery, JavaScript, .net framework, WCF, WPF/Silverlight,SSIS, SSRS, asp.net MVC.

While not working loves Photography and bike riding. Playing computer games are the best stress buster for him Smile | :)

Comments and Discussions

 
QuestionExcellent Pin
JQuery Geeks21-Oct-11 18:40
JQuery Geeks21-Oct-11 18:40 
good job
AnswerRe: Excellent Pin
kiran dangar21-Oct-11 18:44
kiran dangar21-Oct-11 18:44 
QuestionNice solution Pin
Cloud Hsu3-Oct-11 19:51
Cloud Hsu3-Oct-11 19:51 
AnswerRe: Nice solution Pin
kiran dangar3-Oct-11 19:57
kiran dangar3-Oct-11 19:57 
Generalsolution Pin
HalfHuman2-Mar-10 20:41
HalfHuman2-Mar-10 20:41 
GeneralRe: solution Pin
kiran dangar2-Mar-10 21:04
kiran dangar2-Mar-10 21:04 
Generalnice Pin
HalfHuman1-Mar-10 23:22
HalfHuman1-Mar-10 23:22 
GeneralRe: nice Pin
kiran dangar2-Mar-10 17:37
kiran dangar2-Mar-10 17:37 
GeneralMicrosoft Enterprise Library Error Handling Block Pin
Bibhas Paul25-Feb-10 17:12
Bibhas Paul25-Feb-10 17:12 
GeneralRe: Microsoft Enterprise Library Error Handling Block Pin
kiran dangar25-Feb-10 17:42
kiran dangar25-Feb-10 17:42 
GeneralRe: Microsoft Enterprise Library Error Handling Block Pin
kiran dangar25-Feb-10 17:46
kiran dangar25-Feb-10 17:46 
QuestionInteresting Idea have you used the database for error logging? Pin
spoodygoon25-Feb-10 4:46
spoodygoon25-Feb-10 4:46 
AnswerRe: Interesting Idea have you used the database for error logging? Pin
kiran dangar25-Feb-10 17:55
kiran dangar25-Feb-10 17:55 
GeneralRe: Interesting Idea have you used the database for error logging? Pin
spoodygoon26-Feb-10 4:44
spoodygoon26-Feb-10 4:44 
GeneralRe: Interesting Idea have you used the database for error logging? Pin
kiran dangar26-Feb-10 17:27
kiran dangar26-Feb-10 17:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.