I do not like EnsureSuccessStatusCode as it does not return anything serious. This is why I created my own extension:
public static class HttpResponseMessageExtensions { public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } var content = await response.Content.ReadAsStringAsync(); if (response.Content != null) response.Content.Dispose(); throw new SimpleHttpResponseException(response.StatusCode, content); } } public class SimpleHttpResponseException : Exception { public HttpStatusCode StatusCode { get; private set; } public SimpleHttpResponseException(HttpStatusCode statusCode, string content) : base(content) { StatusCode = statusCode; } }
source code for Microsoft EnsureSuccessStatusCode can be found here
Synchronous version based on SO Link :
public static void EnsureSuccessStatusCode(this HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (response.Content != null) response.Content.Dispose(); throw new SimpleHttpResponseException(response.StatusCode, content); }
What I don't like about IsSuccessStatusCode is that it is not "beautifully" reusable. For example, you can use a library, for example polly , to repeat the request in case of a network problem. In this case, you need your code to raise the exception so that a political or some other library can handle it ...
pajics Jan 16 '15 at 14:43 2015-01-16 14:43
source share