Mar*_*age 3 .net c# logging exception
我目前正在对Windows服务进行维护,并且在代码中的某些点处存在一些异常处理(例如,来自计时器和其他外部事件的回调):
try {
...
}
catch (Exception ex) {
_logger.Log("Unhandled exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
Environment.FailFast("Fatal error.");
}
Run Code Online (Sandbox Code Playgroud)
记录异常信息有助于排除出错的问题.但是,有时候有趣的信息是内部异常,这使得很难确定问题的根本原因.例如,a TypeInitializationException很难理解.
是否有更好的方法来记录异常信息以进行故障排除?
是否有更好的方法来记录异常信息以进行故障排除?
就在这里.不要"聪明"并使用ex.Message和ex.StackTrace.只是用ex.ToString().它将递归到内部异常(如果需要,可以是多个级别)并显示完整的堆栈跟踪.
try {
...
}
catch (Exception ex) {
_logger.Log("Unhandled exception:\r\n{0}", ex);
Environment.FailFast("Fatal error.");
}
Run Code Online (Sandbox Code Playgroud)
为了提供一个小例子,如果您创建一个在类的静态构造函数中抛出异常的类的实例,那么这就是您所获得的.这个异常抛出将包装在一个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行.