从你的代码,通过
while
,我想你想把第一个例外
AggregateException
要做到这一点,你可以使用
Flatten
将AggregateException实例展平为单个新实例。
它有助于将异常置于“相同的层次结构”中,然后您可以简单地调用
FirstOrDefault
获取第一个异常。
假设此代码:
Task.Factory.StartNew(
async () =>
{
await Task.Factory.StartNew(
() => { throw new Exception("inner"); },
TaskCreationOptions.AttachedToParent);
throw new Exception("outer");
}).Wait();
}
例外的结构
AggregateException
Exception: outer
AggregateException
Exception: inner
用
Flatten
我可以得到
inner
catch(AggregateException ex)
{
Console.WriteLine(ex.Flatten().InnerExceptions.FirstOrDefault().Message);
}
但是没有
压扁
我得到
聚合例外
,这不正确
Catch(聚合异常)
{
console.writeline(例如flatten().innerExceptions.firstOrDefault().message);
}
对于您的案例,这一行可以帮助您获得第一个异常
ex.Flatten().InnerExceptions.FirstOrDefault().Message
你也有方法
Handle
,帮助您处理内部异常
聚合例外
catch (AggregateException ex)
{
ex.Handle(x =>
{
if (x is UnauthorizedAccessException)
{
//the exception you interested
throw x;
}
// Other exceptions will not be handled here.
//some action i.e log
return false;
});
}