1

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?

jkj2000
  • 1,563
  • 4
  • 19
  • 26

1 Answers1

3

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.
}
Diego
  • 16,436
  • 26
  • 84
  • 136
  • I think that should be `response.EnsureSuccessStatusCode();`. Looks like you copied that typo in from the article. – juharr Jul 08 '15 at 18:12
  • I didn't realize. Thanks @juharr! – Diego Jul 08 '15 at 18:14
  • Thanks. I inherited the code above, which has been out there for a while, and wondered if we needed to do a Task.WaitAll in there. Unfortunately we're on .Net 4.0 so async and await aren't available to us, and the needed fixes to get them on there just aren't going to happen on this system. – jkj2000 Jul 08 '15 at 18:53