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();
}
A place for me to store and share some notes about technical stuff I'm working with at the moment.
The views expressed on this blog are mine alone and do not necessarily reflect the views of my employer.
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment