Search code examples
c#exceptionaggregateexception

Why isn't my try/catch block catching System.AggregateException?


I have some code that makes an asynchronous http call like so:

try
{
  var myHttpClient = new HttpClient();
  var uri = "http://myendpoint.com";

  HttpResponseMessage response = client.GetAsync(uri).Result;
}
catch (Exception ex)
{
  Console.WriteLine("an error occurred");
}

Most of the time this works fine, but occasionally I'll get a System.AggregateException which reads 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

My catch statement is never reached in the case above, and I'm not sure why. I know that Tasks have some complicating factors when they throw exceptions but what I don't know is how to go about handling them in my catch statement?


Solution

  • The exception is not thrown in the same thread of your try/catch. That's why your catch block is not executed.

    Check 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.
    }