I’m currently doing maintenance on a Windows service and at certain points in the code there is some exception handling (e.g. in callbacks from timers and other external events):
try {
...
}
catch (Exception ex) {
_logger.Log("Unhandled exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
Environment.FailFast("Fatal error.");
}
Logging the exception information helps troubleshooting what went wrong. However, sometimes the interesting information is the inner exception which makes it hard to determine the root cause of the problem. For instance a TypeInitializationException can be hard to understand.
Is there a better way to log exception information for troubleshooting purposes?
Yes there is. Don’t be “smart” and use
ex.Messageandex.StackTrace. Just useex.ToString(). It will recurse into inner exceptions (multiple levels if required) and show the complete stacktrace.To provide a small example, this is what you get if you create an instance of a class that throws an exception in the static constructor of the class. This exception throw will be wrapped in a
TypeInitializationException.Before:
Not very helpful. It is hard to determine what went wrong.
After:
Now you can quite easily determine the root cause of the problem being a duplicate key in a dictionary and pinpoint it to line 43 in the source file.