MSB
MSB

Reputation: 65

Is this the wrong way to handle AggregateException with Tasks

Need to handle AggregateExceptions gracefully. Is this way correct?

try
{
    var message = await _queue.ReceiveAsync();
    // rest of code
    //
    var response = await process(body);
}
catch (AggregateException ae)
{
    foreach (var e in ae.InnerExceptions)
    {
         Trace.TraceError(e.Message);
    }
}

Upvotes: 3

Views: 385

Answers (2)

dcastro
dcastro

Reputation: 68720

As @erikkallen pointed out, you shouldn't be getting AggregateExceptions if you're using await.

But, if you weren't, you'd be handling them wrong.

An aggregate exception can actually be a tree of exceptions (i.e., it can contain other AggregateExceptions, which in turn contain more exceptions, etc). For that reason, you should use Flatten:

foreach (var e in ae.Flatten().InnerExceptions)

See Attached Child Tasks and Nested AggregateExceptions on MSDN.

Upvotes: 2

erikkallen
erikkallen

Reputation: 34411

await unwraps AggregateExceptions, so there is no need to do what you're doing. However, if you had done var response = process(body).Result, then your handling would have been necessary.

Upvotes: 1

Related Questions