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

时间:2015-07-08 18:04:27

标签: c# exception 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语句中处理它们?

1 个答案:

答案 0 :(得分:3)

异常不会在try / catch的同一个线程中抛出。这就是为什么你的catch块没有被执行的原因。

检查this article about HttpClient

try
{
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    response.EnsureSuccessStatusCode();    // Throw if not a success code.

    // ...
}
catch (HttpRequestException e)
{
    // Handle exception.
}
相关问题