In an ASP.Net Core web service if an HttpClient.GetStringAsync call fails for 404 error or whatever, it throws an HttpRequestException. This is great.
If on the other hand an HttpClient.PostAsync call fails for 404, it does not throw an exception. I have to check the status code, fabricate an exception and throw it manually.
Why the discrepency, and is there a more elegant way of dealing with this?
HttpResponseMessage response = await _http.PostAsync("api/pollapi/request", new StringContent(requestInput));
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Response status does not indicate success: {(int)response.StatusCode} ({response.StatusCode}).");
}
You can use HttpResponseMessage.EnsureSuccessStatusCode
method that:
Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With