Let's say I have an Interface:
interface A {
string Do();
}
and then I implement this interface in a class. The implementation requires some async operations. Something like the following:
class B : A {
public string Do() {
return Task1().Result;
}
private async Task<string> Task1() {
var str = await Task2();
return str + "task1";
}
private async Task<string> Task2() {
using (WebClient client = new WebClient())
{
return System.Text.Encoding.UTF8.GetString(await client.DownloadDataTaskAsync(new Uri("http://test.com")));
}
}
}
What is the proper way to return, to the external calling code, the first exception that occurs in the async operations chain? Is the following a good approach?
public string Do() {
try {
return Task1().Result;
} catch (AggregateException ex) {
Exception inner = ex;
while(inner.InnerException != null) {
inner = inner.InnerException;
}
throw inner;
}
}
From your code, through the
while
, I think you want to throw the first exception inAggregateException
To do that, you can use FlattenIt helps to put the exceptions in "the same hierarchy", you can then simply call
FirstOrDefault
to get the first exception.Supposed this code:
The stucture of exceptions likes
With
Flatten
, I can getinner
but without
Flatten
, I getAggregateException
, which isn't correctWith your case, this line can help you get the first exception
You have also the method Handle, which help you handle the exception inside
AggregateException