【发布时间】:2015-01-06 20:25:53
【问题描述】:
是否有任何方法(或库可能)可以将 C# 异常(包括 SQL 和实体框架)转换为包含任何特定数据到异常以及 InnerException 的字典?
【问题讨论】:
-
异常类有数据属性字典?不清楚你想要什么。
标签: c# exception logging exception-handling
是否有任何方法(或库可能)可以将 C# 异常(包括 SQL 和实体框架)转换为包含任何特定数据到异常以及 InnerException 的字典?
【问题讨论】:
标签: c# exception logging exception-handling
我认为这是您需要自己编写的内容。试试这样的:
public IDictionary<string, object> ToDictionary(Exception ex)
{
var returnValue = new Dictionary<string, object>();
returnValue.Add("Message", ex.Message);
returnValue.Add("...", ex....);
return returnValue;
}
但是这里没有内置函数...
【讨论】:
这就是我想要的。但是将异常序列化为 json 会更好。
public static Dictionary<string, object> ToDictionary(this Exception ex)
{
var exceptionData = ex.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.Name != "InnerException")
.ToDictionary(prop => prop.Name, prop => prop.GetValue(ex, null));
exceptionData.Add("Type", ex.GetType().ToString());
if (ex.InnerException != null)
{
var innerExceptionData = ex.InnerException.ToDictionary();
if ((exceptionData != null) && (innerExceptionData != null))
{
foreach (var keyPair in innerExceptionData)
{
exceptionData.Add(string.Format("InnerException.{0}", keyPair.Key), keyPair.Value);
}
}
}
return exceptionData;
}
【讨论】: