1

I have a .NET 4 client app using HttpClient. When the _tokenServiceUrl does not correctly resolve via DNS (for example: a network change change occurs when a VPN goes up or down or when mobile devices lose connectivity in a dead spot) then an AggregateException gets thrown. I'm trying to catch that exception, but can't.

    try
    {
        var response = _client.GetAsync(_tokenServiceUrl).Result;

        response.EnsureSuccessStatusCode();
        var token = response.Content.ReadAsAsync<string>().Result;
        return token;

    }
    catch (AggregateException exception)
    {
        Disconnected(exception);
        return string.Empty;
    }

I've mucked around with adding a ContinueWith in order to trap the exception and handle it, but I never return. What can I do to kill the task, given such an exception?

4
  • You should be able to capture that Aggregate exception. Make sure you are not running Fiddler, or some other proxy, when testing. If you do, then an exception won't occur during the GetAsync. You will just get at 502 response and then EnsureSuccessStatusCode will throw a HttpRequestException. Commented Feb 25, 2014 at 21:03
  • Just running through Visual Studio. The AggregateException gets thrown by .Result. It never get's to the response.EnsureSuccessStatusCode(); line. Commented Feb 25, 2014 at 21:14
  • So why can't you catch it then? It catches fine for me. Commented Feb 25, 2014 at 21:18
  • Hmm... you're right. I just spun up a console app to remove all the other cruft and it catches for me as well. I'll have to spend time looking at the way we're injecting the HttpClient... or the version we're using via NuGet... or a conflict of some kind. Anyway, drop an answer telling me I'm daft and I'll accept. Commented Feb 25, 2014 at 21:33

1 Answer 1

1

You should be able to capture that Aggregate exception.

Make sure you are not running Fiddler, or some other proxy, when testing. If you do, then an exception won't occur during the GetAsync. You will just get at 502 response and then EnsureSuccessStatusCode will throw a HttpRequestException.

Sign up to request clarification or add additional context in comments.

3 Comments

Figured out more... Visual Studio was set to "Break when an exception is: Thrown & User-unhandled". If I turn off Thrown, it nicely jumps to the Catch. My test console app was defaulted to Thrown being unchecked... which was the difference. Embarrassingly, if I would have stepped into the next line instead of assuming the Visual Studio trapped error was fatal, it would have caught in the Catch block.
@MikeL We've all been there. :-)
If somebody is experiencing the same problem: Just keep pressing "Continue" or disable (untick) the "Common Language Runtime Exceptions"-Checkbox in the Exception Settings (Visual Studio)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.