我有一些代码,使异步http调用像这样:
try
{
var myHttpClient = new HttpClient();
var uri = "http://myendpoint.com";
HttpResponseMessage response = client.GetAsync(uri).Result;
}
catch (Exception ex)
{
Console.WriteLine("an error occurred");
}
大多数情况下这工作得很好,但偶尔我会得到一个System.AggregateException
,读取One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled. --- End of inner exception stack trace
异常不是在try/catch的同一个线程中抛出的。这就是为什么你的catch块没有被执行。
查看有关HttpClient
的文章:
try
{
HttpResponseMessage response = await client.GetAsync("api/products/1");
response.EnsureSuccessStatusCode(); // Throw if not a success code.
// ...
}
catch (HttpRequestException e)
{
// Handle exception.
}