Tuesday, July 26, 2011

Error Handling Code for Web Part

I keep needing to write the same error handling code for Web Parts, HTML pages, etc. The only difference is in how I display the error. This is something I wrote for a client who told me that he wanted the web part to look ugly if an exception is thrown. Well, this does just that! The label with ID lblError is invisible until DisplayException gets called.
private void DisplayException(Exception ex)
{
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
{

// show exception message
HtmlWriteLine("Exception", ex.Message, htmlTextWriter);
HtmlWriteLine("Method", ex.TargetSite, htmlTextWriter);
HtmlWriteLineReplaceNewLines("Stack Trace", ex.StackTrace, htmlTextWriter);

Exception exInner = ex.InnerException;
int innerExceptionNum = 1;
while (exInner != null)
{
htmlTextWriter.WriteBreak();
htmlTextWriter.Write("-----");
htmlTextWriter.WriteBreak();

HtmlWriteLine(String.Format("Inner Exception {0}", innerExceptionNum), exInner.Message, htmlTextWriter);
HtmlWriteLine("Method", exInner.TargetSite, htmlTextWriter);
HtmlWriteLineReplaceNewLines("Stack Trace", exInner.StackTrace, htmlTextWriter);

exInner = exInner.InnerException;
innerExceptionNum++;

htmlTextWriter.WriteBreak();
}
lblError.Text = stringWriter.ToString();
lblError.Visible = true;
}
}
}

private void HtmlWriteLineReplaceNewLines(string label, string text, HtmlTextWriter htmlTextWriter)
{
htmlTextWriter.Write(String.Format("{0}=", label));
string[] textArray = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string s in textArray)
{
htmlTextWriter.Write(s);
htmlTextWriter.WriteBreak();
}
}

private static void HtmlWriteLine(string label, Object value, HtmlTextWriter htmlTextWriter)
{
htmlTextWriter.Write(String.Format("{0}=\"{1}\"", label, value));
htmlTextWriter.WriteBreak();
}

No comments: