.NET:如何异常转换成字符串? [英] .NET: How to convert Exception to string?
问题描述
当一个异常被抛出(而在IDE调试),我有机会的查看详情的异常:
When an exception is thrown (while debugging in the IDE), i have the opportunity to view details of the exception:
< IMG SRC =http://i.stack.imgur.com/NNcx3.pngALT =在这里输入的形象描述>
但在代码中,如果我打电话 exception.ToString()
我不明白,看那些有用的细节:
But in code if i call exception.ToString()
i do not get to see those useful details:
System.Data.SqlClient.SqlException (0x80131904): Could not find stored procedure 'FetchActiveUsers'.
[...snip stack trace...]
但Visual Studio有一些魔术在那里可以的异常复制到剪贴板的:
这给有用的细节:
System.Data.SqlClient.SqlException was unhandled by user code
Message=Could not find stored procedure 'FetchActiveUsers'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=2812
Procedure=""
Server=vader
State=62
StackTrace:
[...snip stack trace...]
InnerException:
那么我想,
什么是内容:
String ExceptionToString(Exception ex)
{
//todo: Write useful routine
return ex.ToString();
}
这也能完成同样的魔术。有建于某处.NET函数?是否例外
有一个秘法的地方将其转换为字符串?
that can accomplish the same magic. Is there a .NET function built in somewhere? Does Exception
have a secret method somewhere to convert it to a string?
推荐答案
错误码
是特定于 ExternalException
,而不是例外
和 LINENUMBER
和编号
特定于的SQLException
,而不是例外
。因此,只有这样,才能对例外
不同于一般的扩展方法这些属性是使用反射来遍历所有的公共属性。
ErrorCode
is specific to ExternalException
, not Exception
and LineNumber
and Number
are specific to SqlException
, not Exception
. Therefore, the only way to get these properties from a general extension method on Exception
is to use reflection to iterate over all of the public properties.
所以你必须要这样说:
public static string GetExceptionDetails(this Exception exception) {
var properties = exception.GetType()
.GetProperties();
var fields = properties
.Select(property => new {
Name = property.Name,
Value = property.GetValue(exception, null)
})
.Select(x => String.Format(
"{0} = {1}",
x.Name,
x.Value != null ? x.Value.ToString() : String.Empty
));
return String.Join("\n", fields);
}
(没有测试过compliation的问题。)
(Not tested for compliation issues.)
.NET 2.0兼容的回答:
.NET 2.0 compatible answer:
public static string GetExceptionDetails(this Exception exception)
{
PropertyInfo[] properties = exception.GetType()
.GetProperties();
List<string> fields = new List<string>();
foreach(PropertyInfo property in properties) {
object value = property.GetValue(exception, null);
fields.Add(String.Format(
"{0} = {1}",
property.Name,
value != null ? value.ToString() : String.Empty
));
}
return String.Join("\n", fields.ToArray());
}
这篇关于.NET:如何异常转换成字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!