为什么我的 try/catch 块捕获 System.AggregateException?



我有一些代码,使异步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

在上面的例子中,我的catch语句从未到达,我不确定为什么。我知道任务有一些复杂的因素,当他们抛出异常,但我不知道的是如何去处理他们在我的catch语句?

异常不是在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.
}

相关内容

最新更新