6

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?

Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
Buthrakaur
  • 1,821
  • 3
  • 23
  • 35

1 Answers1

5

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")

Jehof
  • 34,674
  • 10
  • 123
  • 155
  • 5
    You're right, but is this really intended and meaningful behavior? It's quite dangerous especially for logging of such exceptions - you just loose part of the exception. I'd say it's a bug :) I don't see any meaningful reason for this behavior. – Buthrakaur Dec 23 '15 at 12:34
  • @Buthrakaur I think not that this is a bug. You should not use the base Exception class. Use a custom one and provide an override of ToString() if you want to change the behavior – Jehof Dec 23 '15 at 12:44
  • @Buthrakaur You should also note that the class Exception exits long time before AggreagateException was implemented. – Jehof Dec 23 '15 at 13:18
  • Thanks for the [reference source link](http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,c3193c051cbb0f3b), I must endeavor to spend more time in that place. – Chris O Jan 12 '17 at 13:49
  • 1
    For every Exception type I'm aware of, the ToString() method accessed from the base Exception.ToString() dumps the entirety of the information in the Exception... with the (ahem) exception of AggregateException. The hugely valuable takeaway here for me is that casting the exception down to AggregateException so you can call its ToString() will dump all the aggregated exceptions. (Still feels like a bug.) – ALEXintlsos Mar 23 '18 at 18:42