Why does HttpClient.PostAsync not throw on failure?

Neu*_*ino 3 c# asp.net

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}).");
}
Run Code Online (Sandbox Code Playgroud)

Yur*_*rii 6

You can use HttpResponseMessage.EnsureSuccessStatusCode method that:

Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.