我目前正在对 Windows 服务进行维护,并且在代码中的某些点有一些异常处理(例如在来自计时器和其他外部事件的回调中):
try {
...
}
catch (Exception ex) {
_logger.Log("Unhandled exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
Environment.FailFast("Fatal error.");
}
记录异常信息有助于解决问题。然而,有时有趣的信息是内部异常,这使得很难确定问题的根本原因。例如,TypeInitializationException
可能很难理解。
有没有更好的方法来记录异常信息以进行故障排除?
最佳答案
Is there a better way to log exception information for troubleshooting purposes?
是的。不要太“聪明”,不要使用 ex.Message
和 ex.StackTrace
。只需使用 ex.ToString()
。它将递归到内部异常(如果需要,则为多个级别)并显示完整的堆栈跟踪。
try {
...
}
catch (Exception ex) {
_logger.Log("Unhandled exception:\r\n{0}", ex);
Environment.FailFast("Fatal error.");
}
举个小例子,如果你创建了一个在类的静态构造函数中抛出异常的类的实例,你会得到这样的结果。此异常抛出将包装在 TypeInitializationException
中。
之前:
Unhandled exception: The type initializer for 'SomeClass' threw an exception. at SomeNamespace.SomeClass..ctor() at SomeNamespace.Callback() in c:\ExceptionHandlingDemo.cs:line 34
帮助不大。很难确定哪里出了问题。
之后:
Unhandled exception: System.TypeInitializationException: The type initializer for 'SomeClass' threw an exception. ---> System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at SomeNamespace.SomeClass..cctor() in c:\ExceptionHandlingDemo.cs:line 43 --- End of inner exception stack trace --- at SomeNamespace.SomeClass..ctor() at SomeNamespace.Callback() in c:\ExceptionHandlingDemo.cs:line 34
现在您可以很容易地确定问题的根本原因是字典中的重复键,并将其精确定位到源文件中的第 43 行。
关于c# - 如何记录异常信息以进行故障排除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11898293/