Wednesday, October 10, 2007

Cute method for logging exceptions

Here is a cute method which returns a string composed of exception (and all its inner exceptions) message and stack trace:


public static String GetExceptionUberStackTrace(Exception e)
{
if (null == e) throw new ArgumentException("Exception parameter shouldn't be null!");
String result = "";

do {
result += String.Format("Message: {0}{1}", e.Message, Environment.NewLine);
result += String.Format(
"Stack trace: {0}{1}{2}",
Environment.NewLine,
e.StackTrace,
Environment.NewLine
);

e = e.InnerException;

if (null != e)
{
result += String.Format("{0}Inner exception:{1}",
Environment.NewLine, Environment.NewLine);
}
else
{
break;
}

} while (true);

return result;
}

1 comment:

Unknown said...

I would change:

result += String.Format(
"Stack trace: {0}{1}{2}",
Environment.NewLine,
e.StackTrace,
Environment.NewLine

to result += string.Format(
"Stack trace: {0}{1}{0}",
Environment.NewLine,
e.StackTrace);

And remove braces for if/else.