Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapped AggregateException reports just first exception in ToString method

I get complete set of nested exceptions when I use ToString() method on AggregateException directly:

public void GreenTest()
{
    var ex = new AggregateException(new Exception("ex1"), new Exception("ex2"));

    ex.ToString()
        .Should()
        .Contain("ex1")
        .And
        .Contain("ex2");
}

The problem is I get only the first exception when the AggregateException is wrapped in another exception:

public void RedTest()
{
    var ex = new Exception("wrapper", new AggregateException(new Exception("ex1"), new Exception("ex2")));

    ex.ToString()
        .Should()
        .Contain("wrapper")
        .And
        .Contain("ex1")
        .And
        .Contain("ex2");
}

ex2 isn't present in the resulting string. Is this a bug or some well-known feature of AggregateException class?

like image 934
Buthrakaur Avatar asked Dec 23 '15 10:12

Buthrakaur


People also ask

How do I fix AggregateException occurred?

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program. This will show you the original exception when it was thrown in the first place. (comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.

How do you flatten AggregateException?

To avoid having to iterate over nested AggregateException exceptions, you can use the Flatten method to remove all the nested AggregateException exceptions, so that the InnerExceptions property of the returned AggregateException object contains the original exceptions.

When would you use an aggregate exception?

AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query.

Does await throw AggregateException?

When using await, it's going to unwrap the first exception and return it, that's why we don't hit the catch (AggregateException e) line.


1 Answers

I think not that this is a bug. More a normal behavior

The problem is that the ToString() on Exception will not call the ToString() of the innerException, but the private ToString(bool,bool) method on the exception class itself.

So the overridden ToString() method of the AggregateException is not called.

The constructor of the AggregateException will set the innerException to the first exception passed to the constructor.

In your case this is new Exception("ex1")

like image 61
Jehof Avatar answered Nov 10 '22 08:11

Jehof