Not all HttpRequestException's have a valid HTTP response to have a status code. That particular function, EnsureSuccessStatusCode is the one exception to that rule. Normally, HttpRequestException is returned when there are errors in getting any HTTP response at all. Hence, there is usually not a status code since there is no response message returned.
We can't add any new APIs to the current 4.1 Http contract. Why do you need this particular field added to the HttpRequestException.
@davidsh I'm building a client application that is consuming an API and I want to be able to handle failed requests.
I know that the API will return specific status codes like 401 Unauthorized and I would like to be able to interpret that status code and throw my own exception types.
For example:
try
{
using (var client = new HttpClient())
{
using (var response = client.GetAsync("someValidUrl"))
{
response.EnsureSuccessStatusCode();
// Do some more work here
}
}
}
catch (HttpRequestException ex)
{
// Interpret failed request from Http status code
}
I could declare a HttpResponseMessage outside the try/catch but I was really hoping the original exception thrown would have some additional data.
Does that seem like it's standard consumption for the HttpClient?
The only time that an HttpRequestException could be thrown in the case of a successful request/response transaction is from the EnsureSuccessStatusCode call. That is a narrow set of conditions for which all other HttpRequestException throws won't have a StatusCode at all. So, it doesn't seem generalized enough to add a StatusCode property to HttpRequestException when it will always be null except in this particular case.
I would suggest refactoring your code above to handle that.
please reconsider this. EnsureSuccessStatusCode _should_ throw an exception that indicates the status code. either add it to HttpRequestException, or throw a different exception.
Most helpful comment
please reconsider this. EnsureSuccessStatusCode _should_ throw an exception that indicates the status code. either add it to HttpRequestException, or throw a different exception.