In this post I’ll show how I handle exceptions in the projects I develop.

Some time ago I wrote a simple class which turned out to be very useful in exception handling and displaying it to the user. To use it You have to create a new instance of it and add it to the controls collection on the page. Then You can just add exceptions, through the appropriate method, which will be rendered as a HTML table. The class uses Render event to check if any exception has been added, if so the class renders appropriate HTML code which is shown to the user.


public class ExceptionsManager : UserControl
{
private List<ExceptionObject> _exceptions;

public IList<ExceptionObject> Exceptions
{
get
{
return _exceptions.AsReadOnly();
}
}

public ExceptionsManager()
{
_exceptions = new List<ExceptionObject>();
}

public void AddException(Exception ex)
{
AddException(String.Empty, ex);
}

public void AddException(string message, Exception ex)
{
_exceptions.Add(new ExceptionObject(message, ex));
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);

if (_exceptions.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("<table width='100%' cellpadding='0' cellspacing='0'>");

int i = 0;
foreach (ExceptionObject eo in _exceptions)
{
i++;
string errorDivIdMain = "dError_" + this.ID + "_" + i;
sb.Append("<tr><td style='color: red'>" + i + "." + (String.IsNullOrEmpty(eo.Message) ? String.Empty : " <b>" + eo.Message + "</b>.") + " " + eo.Exception.Message + " <a href='' onclick='document.getElementById(\"" + errorDivIdMain + "\").style.display=\"block\"; return false;'>[Show Stack Trace]</a><div id=\"" + errorDivIdMain + "\" style=\"display: none\"><br />" + eo.Exception.StackTrace + "</div><br /></td></tr>");

int padding = 0;
Exception ex = eo.Exception;
while (ex.InnerException != null)
{
ex = ex.InnerException;
padding += 30;
string errorDivId = "dError_" + this.ID + "_" + i + "_" + padding;
sb.Append("<tr class='" + errorDivIdMain + "' style='display: none'><td style='color: red; padding-left: " + padding + "px'><b>INNER EXCEPTION:</b> " + ex.Message + " <a href='' onclick='document.getElementById(\"" + errorDivId + "\").style.display=\"block\"; return false;'>[Show Stack Trace]</a><div id=\"" + errorDivId + "\" style=\"display: none\"><br />" + ex.StackTrace + "</div><br /></td></tr>");
}
}

sb.Append("</table>");

writer.Write(sb.ToString());
}
}
}

public class ExceptionObject
{
public string Message { get; private set; }
public Exception Exception { get; private set; }

public ExceptionObject(string message, Exception ex)
{
Message = message;
Exception = ex;
}
}

To use it:


protected void Page_Load(object sender, EventArgs e)
{
ExceptionsManager exMgr = new ExceptionsManager();
this.Controls.Add(exMgr);

try
{
Int32.Parse("TEST");
}
catch (Exception ex)
{
exMgr.AddException(ex);
}
}

Above code will result in the error:

After clicking Show Stack Trace: