Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real exception type that is contained in AggregateException

a database query is performed in a task which has a CancellationToken of 59sec. If the task is cancelled, a TaskCanceledException is thrown. But this exception is catched as part of a AggregateException. I want to provide a specific error message. So is it possible to validate in the code if the real exception in the AggregateException is a TaskCancelationException?

like image 663
Anton Sterr Avatar asked Apr 03 '17 11:04

Anton Sterr


1 Answers

You need to use InnerException or InnerExceptions, depending on your situation:

if (x.InnerException is TaskCanceledException)
{
    // ...
}

The above will work if you know you only have one exception; however, if you have multiple, then you want to do something with all of them:

var sb = new StringBuilder();

foreach (var inner in x.InnerExceptions)
{
    sb.AppendLine(inner.ToString());
}

System.Diagnostics.Debug.Print(sb.ToString()); 
like image 98
rory.ap Avatar answered Nov 14 '22 22:11

rory.ap