DNS resolution failure in HttpClient throws Unhand

2019-08-13 01:59发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-08-13 02:36

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.

查看更多
登录 后发表回答