Gabriel S. Gabriel S. - 11 months ago 54
C# Question

Distinguish between HttpClient request failure types

I need to write code to handle the 2 distinct types of failures that can arise after issuing an HTTP request using an

object that comes with .Net Framework 4.5:

  1. Connectivity failures, when the server can not be reached due to connection problems - e.g. no connection available, timeout expiration, incorrect network settings etc.

  2. Although technically not a failure, the case when the request successfully reaches the server but the server responds with an HTTP error status code (e.g. 404, 400, 409, 500 etc.)

It is very important that one failure type is not treated as the other. Which is the correct and reliable way to do this? The
method seems to help with at least the second case, but the documentation is disappointingly scarce.

Answer Source

After some manual testing, the good news is that there seems to be a reliable method to separate the 2 types of errors, but the bad news is that it's not consistently the same on all platforms - at least not on Windows Phone 8. On .Net Framework 4.5 Full and on Windows Store App types of project, the following code does the trick:

            var response = await httpClient.PostAsync(uri, content);

            if (!response.IsSuccessStatusCode)
                // handle the second type of error (404, 400, etc.)
        catch (HttpRequestException ex)
            // handle the first type of error (no connectivity, etc)

On Windows Phone 8, unfortunately, both types are handled under the if condition: IsSuccessStatusCode is set to false and no HttpRequestException (or any other exception, for that matter) is raised. For WP8 I'm using the portable class library implementation of HttpClient (, I asked them if this inconsistency can be fixed, hopefully it can and will soon be.