Get real exception type that is contained in AggregateException
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());
You can get the list of exceptions, or use the first one if there is just one:
var first = agg.InnerException; // just the first
foreach (Exception ex in agg.InnerExceptions) // iterate over all
{
// do something with each and every one
}
Another possible solution
try
{
// the logic
}
catch (AggregateException e) when (e.InnerException is TaskCancelationException castedException)
{
// here castedException is of type TaskCancelationException
}
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/when#when-in-a-catch-statement