Tuesday, May 19, 2015

Impress your colleagues with your knowledge about…AggregateException.Flatten()

Sometimes when working with .NET you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is AggregateException.Flatten().

If you have a task that calls another task that calls another task and so on… and an exception is thrown, you end up with an AggregateException that contains an AggregateException that contains an AggregateException and so on… . If you want to unwrap the real exceptions and get rid of all the intermediate AggregateExceptions, you can use the Flatten method on the top most AggregateException.

An example:

var task = Task.Factory.StartNew(
() =>
{
Task.Factory.StartNew(
() => { throw new Exception("inner"); },
TaskCreationOptions.AttachedToParent);

throw new Exception("outer");
});


If you Wait() on the created task, it will throw an AggregateException, that looks like this:




  • AggregateException


    • Exception: outer


    • AggregateException


      • Exception: inner







Thanks to the Flatten method, the structure is simplified to:




  • AggregateException



    • Exception: outer



      • Exception: inner



No comments: