C#字典异常
本文关键字:异常 字典 | 更新日期: 2023-09-27 18:29:48
是否有任何方法(或库)可以将C#异常(包括SQL和实体框架)转换为字典,该字典将包括异常和InnerException的任何特定数据?
我认为这是您需要自己编写的内容。试试这样的东西:
public IDictionary<string, object> ToDictionary(Exception ex)
{
var returnValue = new Dictionary<string, object>();
returnValue.Add("Message", ex.Message);
returnValue.Add("...", ex....);
return returnValue;
}
但是tj没有内置函数。。。
这就是我想要的。但是将Exception序列化为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;
}