获取包含在 AggregateException 中的真实异常类型

Ant*_*err 6 .net c# exception-handling

在 CancellationToken 为 59 秒的任务中执行数据库查询。如果任务被取消,则抛出 TaskCanceledException。但是这个异常作为 AggregateException 的一部分被捕获。我想提供一个特定的错误信息。那么是否可以在代码中验证 AggregateException 中的真正异常是否是 TaskCancelationException?

adr*_*692 7

另一种可能的解决方案

try
{
    // the logic
}
catch (AggregateException e) when (e.InnerException is TaskCancelationException castedException)
{
    // here castedException is of type TaskCancelationException
}
Run Code Online (Sandbox Code Playgroud)

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/when#when-in-a-catch-statement


Pat*_*man 5

您可以获取异常列表,或者如果只有一个,则使用第一个:

var first = agg.InnerException; // just the first

foreach (Exception ex in agg.InnerExceptions) // iterate over all
{
    // do something with each and every one
}
Run Code Online (Sandbox Code Playgroud)


ror*_*.ap 5

您需要使用InnerExceptionInnerExceptions,具体取决于您的情况:

if (x.InnerException is TaskCanceledException)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您知道只有一个例外,则上述方法将起作用;但是,如果您有多个,那么您想对所有这些都做些什么:

var sb = new StringBuilder();

foreach (var inner in x.InnerExceptions)
{
    sb.AppendLine(inner.ToString());
}

System.Diagnostics.Debug.Print(sb.ToString()); 
Run Code Online (Sandbox Code Playgroud)