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?
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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With