【问题标题】:How to get the root causing exception from an AggregatedException如何从 AggregateException 获取导致异常的根源
【发布时间】:2016-06-01 09:18:16
【问题描述】:

我正在使用Task 加载数据。如果失败,我想向用户展示失败的根本原因。

Task 执行期间发生的异常被聚合到AggregatedException。那么,从中获取导致异常的根源的最佳方法是什么?

我目前的做法是:

public static Exception GetRootCausingException(this AggregateException aggregatedException)
{
    if (aggregatedException == null)
        return null;

    // get the AggregateException that is the root cause of this exception.
    var exception = aggregatedException.GetBaseException();
    while (exception.InnerException != null) exception = exception.InnerException;
    return exception;
}

【问题讨论】:

  • 最里面的异常通常是没有意义的。外层经常添加或解释信息。您可能应该去掉 aggex,然后显示所有异常(例如 ToString)。

标签: c# exception-handling task-parallel-library task


【解决方案1】:

AggregatedException 表示一个或多个异常。这意味着您可以有多个“根本异常”,因此您必须处理多个异常并查找每个异常的根本问题。

您可以使用 AggregatedException 的 Handle 方法来执行此操作,该方法在每个异常上调用一个处理程序:

catch (AggregateException ae) {
       ae.Handle((x) =>
         {
             // look for the route cause of exception x
         });
  }

See the documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多