I am making asynchronous requests and I am storing them in a list Task
, at the end of the iteration, that is, since it sends all the requests, I use the method WhenAll().Result
to capture all the responses once the requests have finished and save them in an array, as shown in the following code:
try
{
IEnumerable<Task<string>> task = requestArray.Select((a, i) =>
{
var fareIds = new List<string>();
var ticketsId = new List<string>();
var seatsNumber = new List<string>();
for (var posSeat = 0; posSeat < requestArray[i].seats.Length; posSeat++)
{
fareIds.Add(requestArray[i].seats[posSeat].fareId.ToString());
ticketsId.Add(requestArray[i].seats[posSeat].ticketId.ToString());
seatsNumber.Add(requestArray[i].seats[posSeat].number.ToString());
}
var xml = BlockSeatRQ(i, seatsNumber.ToArray(), fareIds.ToArray(), ticketsId.ToArray(), tokenRQ);
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/xml");
return Task.Run(() => client.UploadStringTaskAsync(Config.Endpoint + SEAT_BLOCK_URL, "POST", xml));
});
blockSeatResponses = Task.WhenAll(task).Result;
}
catch (WebException e)
{
}
The problem I have is that when an exception arises, it does not enter the catch, but rather it thunders when the method WhenAll
is called, as shown in the following image:
Now the question is, why doesn't it enter the catch? And how can I make it enter the catch? Since the service I am using does not return a specific error to use, it simply allows me to enter Exception
and get the error message.WebException
Body
I hope you understand the problem.
It does not enter
catch
because you are only catching exceptions of the typeWebException
and in that case what you mark in your image is throwing one of the typeAggregateException
. So far the reason.If you want to treat your exceptions specifically you must stack catches with each type and its exclusive treatment, it is always good practice at the end of all the catches to catch the ones of the type
Exception
so your application would not throw an unhandled exception error.An example:
EDITED:
To avoid it
AggregateException
you can use:await
returns theresult
deltask
and unwraps theAggregateException
.