I have this extension method which suits my purposes just fine.
public static class ExceptionExtensions {
public static string ToMessageAndCompleteStacktrace(this Exception exception) {
Exception e = exception;
StringBuilder s = new StringBuilder();
while (e != null) {
s.AppendLine("Exception type: " + e.GetType().FullName);
s.AppendLine("Message : " + e.Message);
s.AppendLine("Stacktrace:");
s.AppendLine(e.StackTrace);
s.AppendLine();
e = e.InnerException;
}
return s.ToString();
}
}
And use it like this:
using SomeNameSpaceWhereYouStoreExtensionMethods;
try {
// Some code that throws an exception
}
catch(Exception ex) {
Console.WriteLine(ex.ToMessageAndCompleteStacktrace());
}
Update
Since I'm receiving upvotes for this answer I want to add that I stopped using this extension method, and now I'm just using exception.ToString()
. It gives more information. So please, stop using this method, and just use .ToString()
. See the answer above.