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

Global Exception Handling in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.35/5 (13 votes)
21 Feb 20022 min read 140.2K   1.3K   61  
An article on handling errors in ASP.NET Applications
using System;
using System.Web;
using System.Web.Mail;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.IO;

namespace XC.Web
{
	public class ErrorHandler
	{
		public const int UseEventLog = 1;
		public const int UseFile = 2;
		public const int UseEmail = 4;
		
		int m_notifyMode = 0;
		
		EmailNotificationSettings m_emailSettings = new EmailNotificationSettings();
		FileNotificationSettings  m_fileSettings  = new FileNotificationSettings();
		EventLogSettings          m_logSettings   = new EventLogSettings();


		public ErrorHandler()
		{
			if (ConfigurationSettings.AppSettings["errorNotifier_NotifyMode"] == null)
			{
				NotifyMode = UseFile;
			}
			else
			{
				NotifyMode = int.Parse(ConfigurationSettings.AppSettings["errorNotifier_NotifyMode"]);
			}
		}

		public int NotifyMode
		{
			get { return m_notifyMode;  }
			set { m_notifyMode = value; }
		}
		
		public EmailNotificationSettings EmailSettings
		{
			get { return m_emailSettings;  }
			set { m_emailSettings = value; }
		}

		public FileNotificationSettings FileSettings
		{
			get { return m_fileSettings;  }
			set { m_fileSettings = value; }
		}

		public EventLogSettings LogSettings
		{
			get { return m_logSettings;  }
			set { m_logSettings = value; }
		}

		public void HandleException()
		{
			Exception e = HttpContext.Current.Server.GetLastError();

			if (e == null)
				return;

			e = e.GetBaseException();
			
			if (e != null)
				HandleException(e);
		}

		public void HandleException(Exception e)
		{
			string sExceptionDescription = FormatExceptionDescription(e);

			if ((NotifyMode & UseFile) == UseFile)
			{
				WriteToFile(sExceptionDescription);
			}

			if ((NotifyMode & UseEmail) == UseEmail)
			{
				SendEmail(sExceptionDescription);
			}			

			if ((NotifyMode & UseEventLog) == UseEventLog)
			{
				LogEvent(sExceptionDescription);
			}
		}

		protected virtual string FormatExceptionDescription(Exception e)
		{
			StringBuilder sb = new StringBuilder();
			HttpContext context = HttpContext.Current;

			sb.Append("Time of Error: " + DateTime.Now.ToString("g") + Environment.NewLine);
			sb.Append("URL: " + context.Request.Url + Environment.NewLine);
			sb.Append("Form: " + context.Request.Form.ToString() + Environment.NewLine);
			sb.Append("QueryString: " + context.Request.QueryString.ToString() + Environment.NewLine);			
			sb.Append("Server Name: " + context.Request.ServerVariables["SERVER_NAME"] + Environment.NewLine);
			sb.Append("User Agent: " + context.Request.UserAgent + Environment.NewLine);
			sb.Append("User IP: " + context.Request.UserHostAddress + Environment.NewLine);
			sb.Append("User Host Name: " + context.Request.UserHostName + Environment.NewLine);
			sb.Append("User is Authenticated: " + context.User.Identity.IsAuthenticated.ToString() + Environment.NewLine);
			sb.Append("User Name: " + context.User.Identity.Name + Environment.NewLine);
			

			while (e != null)
			{				
				sb.Append("Message: " + e.Message + Environment.NewLine);
				sb.Append("Source: " + e.Source+ Environment.NewLine);
				sb.Append("TargetSite: " + e.TargetSite + Environment.NewLine);
				sb.Append("StackTrace: " + e.StackTrace + Environment.NewLine);
				sb.Append(Environment.NewLine + Environment.NewLine);

				e = e.InnerException;
			}
			
			sb.Append("\n\n");
			return sb.ToString();
		}

		void WriteToFile(string sText)
		{
			string sPath = HttpContext.Current.Server.MapPath(FileSettings.Filename);
			try
			{
				FileStream fs = new FileStream(sPath, FileMode.Append, FileAccess.Write);
				StreamWriter writer = new StreamWriter(fs);
				writer.Write(sText);
				writer.Close();
				fs.Close();
			}
			catch (Exception )
			{
			}
		}

		void SendEmail(string sBody)
		{
			MailMessage msg = new MailMessage();

			msg.BodyFormat = MailFormat.Text;
			msg.To         = EmailSettings.To;
			msg.From       = EmailSettings.From;
			msg.Subject    = EmailSettings.Subject;
			msg.Body       = sBody;

			try
			{
				if (EmailSettings.SmtpServer != null)
					SmtpMail.SmtpServer = EmailSettings.SmtpServer;

				SmtpMail.Send(msg);
			}
			catch (Exception )
			{
			}
		}

		void LogEvent(string sText)
		{	
			try
			{
				if (!EventLog.SourceExists(LogSettings.EventSource))
				{
					EventLog.CreateEventSource(LogSettings.EventSource, "Application");
				}

				EventLog log = new EventLog();
				log.Source = LogSettings.EventSource;
				log.WriteEntry(sText, EventLogEntryType.Error);
			}
			catch (Exception )
			{
			}

		}

		public void ClearLoggedFileErrors()
		{
			try
			{
				File.Delete(HttpContext.Current.Server.MapPath(FileSettings.Filename));
			}
			catch (Exception )
			{
			}
		}


	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect VisionOne AG
Switzerland Switzerland
XicoLoko is a brazilian developer based in Switzerland.

Comments and Discussions