Important alert: (current site time 7/15/2013 7:58:12 AM EDT)
 

VB icon

ASP.NET Global Error Handler (with html report & email functionality)

Email
Submitted on: 2/5/2003 7:49:03 PM
By: Joel Thoms  
Level: Beginner
User Rating: By 5 Users
Compatibility: C#, ASP.NET
Views: 22714
(About the author)
 
     Globally capture errors and exceptions in your ASP.NET site. Admin(s) can be emailed a detailed HTML report of the error, then redirect the user to a friendly error page. 100% C#, no external objects needed.

 
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
//**************************************
// for :ASP.NET Global Error Handler (with html report & email functionality)
//**************************************
Copyright 2003 Joel Thoms
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: ASP.NET Global Error Handler (with html report & email functionality)
// Description:Globally capture errors and exceptions in your ASP.NET site. Admin(s) can be emailed a detailed HTML report of the error, then redirect the user to a friendly error page. 100% C#, no external objects needed.
// By: Joel Thoms
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=948&lngWId=10//for details.//**************************************

/* Author: Joel Thoms
 * Website: http://www.joel.net
 * Email: (contact me through website)
 * Date: 02.05.2003
 * 
 * Copyright 2003 Joel Thoms
 *
 * Description:
 *	HtmlError generates an HTML error message from the generated Exception. HtmlError also includes 
 *	a routine to email the error message to the admin(s).
 * 
 *	This object can be used to capture individual errors, though it's best use is to globally capture
 *	errors using Global.asax. Both examples are provided.
 * 
 * 
 * Usage and Examples:
 * 
 *	Here is an example on how to capture a simple division by zero error.
 * 
 *	[C#]
 *		// Division by zero error example
 *		try {
 *			int x = 0;
 *			x = 1 / x;
 *		} catch (Exception Ex) {
 *			// Display Error Message to the browser
 *			Response.Write(HtmlError.getHtmlError(Ex));
 * 
 *			// Don't Specify SMTP Server
 *			HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM");
 * 
 *			// Specify SMTP Server
 *			//HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com");
 *		}
 *
 * 
 * 	[VB.NET]
 *
 *		' Division by zero error example
 *		Try
 *			Dim x As Integer = 0
 *			x = 1 / x
 *		Catch Ex As Exception
 *			' Display Error Message to the browser
 *			Response.Write(HtmlError.getHtmlError(Ex))
 * 
 *			' Don't Specify SMTP Server
 *			HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM")
 * 
 *			' Specify SMTP Server
 *			'HtmlError.sendHtmlError(Ex, "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com")
 *		End Try
 * 
 * 
 *	Here is an example on globally capturing errors using the Global.asax file.
 * 
 *	[C#]
 * 
 * 		protected void Application_Error(Object sender, EventArgs e) {
 *			// Don't Specify SMTP Server
 *			HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM");
 * 
 *			// Specify SMTP Server
 *			//HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com");
 * 
 *			// Redirect User to Friendly Error Page
 *			Response.Redirect("/error.aspx");
 *		}
 * 
 *	[VB.NET]
 *		Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
 *			' Don't Specify SMTP Server
 *			HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM")
 * 
 *			' Specify SMTP Server
 *			'HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com")
 * 
 *			' Redirect User to Friendly Error Page
 *			Response.Redirect("/error.aspx")
 *		End Sub
 * 
 *
*/
using System;
using System.Data;
using System.Web;
using System.Web.Mail;
using System.Collections.Specialized;
/// <summary>HtmlError Object.</summary>
public class HtmlError {
	public HtmlError() { }
	static public void sendHtmlError(Exception Ex, string email_address) { sendHtmlError(Ex, email_address, ""); }
	static public void sendHtmlError(Exception Ex, string email_address, string smtp_server) {
		MailMessage mail = new MailMessage();
		mail.From = "server-errors@discountasp.net";
		mail.To = email_address;
		mail.Subject = "Uncaptured Error";
		mail.Body = getHtmlError(Ex);
		mail.BodyFormat = MailFormat.Html;
		if (smtp_server.Length > 0) SmtpMail.SmtpServer = smtp_server;
		SmtpMail.Send(mail);
	}
	/// <summary>Returns HTML an formatted error message.</summary>
	static public string getHtmlError(Exception Ex) {
		// Heading Template
		const string heading = "<TABLE BORDER=\"0\" WIDTH=\"100%\" CELLPADDING=\"1\" CELLSPACING=\"0\"><TR><TD bgcolor=\"black\" COLSPAN=\"2\"><FONT face=\"Arial\" color=\"white\"><B> <!--HEADER--></B></FONT></TD></TR></TABLE>";
		// Error Message Header
		string html = "<FONT face=\"Arial\" size=\"5\" color=\"red\">Error - " + Ex.Message + "</FONT><BR><BR>";
		// Populate Error Information Collection
		NameValueCollection error_info = new NameValueCollection();
		error_info.Add("Message", cleanHTML(Ex.Message));
		error_info.Add("Source", cleanHTML(Ex.Source));
		error_info.Add("TargetSite", cleanHTML(Ex.TargetSite.ToString()));
		error_info.Add("StackTrace", cleanHTML(Ex.StackTrace));
		// Error Information
		html += heading.Replace("<!--HEADER-->", "Error Information");
		html += CollectionToHtmlTable(error_info);
		// QueryString Collection
		html += "<BR><BR>" + heading.Replace("<!--HEADER-->", "QueryString Collection");
		html += CollectionToHtmlTable(HttpContext.Current.Request.QueryString);
		
		// Form Collection
		html += "<BR><BR>" + heading.Replace("<!--HEADER-->", "Form Collection");
		html += CollectionToHtmlTable(HttpContext.Current.Request.Form);
		// Cookies Collection
		html += "<BR><BR>" + heading.Replace("<!--HEADER-->", "Cookies Collection");
		html += CollectionToHtmlTable(HttpContext.Current.Request.Cookies);
		// Session Variables
		html += "<BR><BR>" + heading.Replace("<!--HEADER-->", "Session Variables");
		html += CollectionToHtmlTable(HttpContext.Current.Session);
		// Server Variables
		html += "<BR><BR>" + heading.Replace("<!--HEADER-->", "Server Variables");
		html += CollectionToHtmlTable(HttpContext.Current.Request.ServerVariables);
		return html;
	}
	static private string CollectionToHtmlTable(NameValueCollection collection) {
		// <TD>...</TD> Template
		const string TD = "<TD><FONT face=\"Arial\" size=\"2\"><!--VALUE--></FONT></TD>";
		// Table Header
		string html = "\n<TABLE width=\"100%\">\n"
			+ " <TR bgcolor=\"#C0C0C0\">" + TD.Replace("<!--VALUE-->", " <B>Name</B>")
			+ " " + TD.Replace("<!--VALUE-->", " <B>Value</B>") + "</TR>\n";
		// No Body? -> N/A
		if (collection.Count == 0) {
			collection = new NameValueCollection();
			collection.Add("N/A", "");
		}
		// Table Body
		for (int i = 0; i < collection.Count; i++) {
			html += "<TR valign=\"top\" bgcolor=\"" + ((i % 2 == 0) ? "white" : "#EEEEEE") + "\">"
				+ TD.Replace("<!--VALUE-->", collection.Keys[i]) + "\n"
				+ TD.Replace("<!--VALUE-->", collection[i]) + "</TR>\n";
		}
		// Table Footer
		return html + "</TABLE>";
	}
	static private string CollectionToHtmlTable(HttpCookieCollection collection) {
		// Overload for HttpCookieCollection collection.
		// Converts HttpCookieCollection to NameValueCollection
		NameValueCollection NVC = new NameValueCollection();
		foreach (string item in collection) NVC.Add(item, collection[item].Value);
		return CollectionToHtmlTable(NVC);
	}
	static private string CollectionToHtmlTable(System.Web.SessionState.HttpSessionState collection) {
		// Overload for HttpSessionState collection.
		// Converts HttpSessionState to NameValueCollection
		NameValueCollection NVC = new NameValueCollection();
		foreach (string item in collection) NVC.Add(item, collection[item].ToString());
		return CollectionToHtmlTable(NVC);
	}
	static private string cleanHTML(string Html) {
		// Cleans the string for HTML friendly display
		return (Html.Length == 0) ? "" : Html.Replace("<", "<").Replace("\r\n", "<BR>").Replace("&", "&").Replace(" ", " ");
	}
}


Other 1 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

2/10/2003 2:00:23 PM

Could you pls. guid, I am getting error on System.web.mail
Please explain your code
DO I have to define using System;
in the C# code: befor the PGM
[C#]
*
* protected void Application_Error(Object sender, EventArgs e) {
* // Don't Specify SMTP Server
* HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM");
*
* // Specify SMTP Server
* //HtmlError.sendHtmlError(Context.Error.GetBaseException(), "YOUR-EMAIL@ADDRESS.COM", "your.smtp-server.com");
*
* // Redirect User to Friendly Error Page
* Response.Redirect("/error.aspx");

Thanks
(If this comment was disrespectful, please report it.)

 
2/10/2003 3:09:19 PMJoel Thoms

You will have to add a reference to System.Web in your project.

Later, I will add a link to download the whole project from my website.
(If this comment was disrespectful, please report it.)

 
2/14/2003 1:34:03 PM

This would not work within a Try-Catch-Finally-End Try scenario, correct?
(If this comment was disrespectful, please report it.)

 
2/14/2003 2:16:38 PMJoel Thoms

I've tested it with a Try/Catch scenario and it works great. I have an example of the Try/Catch up above the code in the comments section if you want to look at how it can be done.
(If this comment was disrespectful, please report it.)

 
3/27/2003 4:11:46 PMTroy Blake

Great Job. I translated the code to VB.Net and am using it in a production ASP.Net project. I'm using it to better format the normal error emails into a user-friendly format.

(If this comment was disrespectful, please report it.)

 
3/27/2003 8:23:13 PMJoel Thoms

I'm glad to hear that. I now use this on every ASP.NET project I work on. I don't know how I ever lived without it.
(If this comment was disrespectful, please report it.)

 
4/18/2003 3:10:20 PMRoger Martin

Excellent! Your code is now a permanent part of our intranet.
(If this comment was disrespectful, please report it.)

 
8/3/2003 1:10:59 AM

Thanks for the info. I am using VB.NET. I have three web forms in my application. Once user clicks button on first form, I want to take the user to second/third web form based on the condition. Do I need to use Response.Redirect("page address") to do this or do you advise any other methods? Please advise.
(If this comment was disrespectful, please report it.)

 
6/30/2007 5:36:11 AMsantosh kumar singh

nice works
(If this comment was disrespectful, please report it.)

 
2/19/2010 7:37:54 AMRavikumar

we are learning .NET through these codes.
(If this comment was disrespectful, please report it.)

 
2/19/2010 8:38:14 AMRavikumar

we are learning .NET coding through this website.


(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.