要仅打印深度异常中的 Messages 部分,您可以执行以下操作:
public static string ToFormattedString(this Exception exception)
{
IEnumerable<string> messages = exception
.GetAllExceptions()
.Where(e => !String.IsNullOrWhiteSpace(e.Message))
.Select(e => e.Message.Trim());
string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
return flattened;
}
public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
yield return exception;
if (exception is AggregateException aggrEx)
{
foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
{
yield return innerEx;
}
}
else if (exception.InnerException != null)
{
foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
{
yield return innerEx;
}
}
}
这递归地遍历所有内部异常(包括AggregateExceptions 的情况)以打印其中包含的所有Message 属性,由换行符分隔。
例如
var outerAggrEx = new AggregateException(
"Outer aggr ex occurred.",
new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());
发生了外部聚集。
内聚集前。
数字格式不正确。
未经授权的文件访问。
不是管理员。
您需要听取其他 Exception 属性以获取更多详细信息。例如Data 会有一些信息。你可以这样做:
foreach (DictionaryEntry kvp in exception.Data)
要获取所有派生属性(不是基于 Exception 类),您可以这样做:
exception
.GetType()
.GetProperties()
.Where(p => p.CanRead)
.Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));