简体   繁体   中英

How to get the root causing exception from an AggregatedException

I am loading data using a Task . In case of failure, I would like to show the user the root cause of the failure.

Exceptions that occure during Task execution are aggregated to an AggregatedException . So, what is is the best way to get the root causing exception from it?

My current approach is:

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;
}

An AggregatedException represents one or more exceptions. This means you can have more than one "root exception" so you have to handle multiple exceptions and look for the root problem for each of them.

You can do it using the Handle method of AggregatedException which invokes a handler on each exception :

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

See the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM