/// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError) { // For 500, we serialize the exception message on the server. HttpExceptionMessage exceptionMessage; try { exceptionMessage = httpResponseMessage.Content.ReadAsAsync<HttpExceptionMessage>().Result; } catch (InvalidOperationException) { // This would happen if the response type is not a Json object. exceptionMessage = new HttpExceptionMessage { ExceptionMessage = httpResponseMessage.Content.ReadAsStringAsync().Result, ExceptionType = typeof(HttpRequestException).Name }; } exceptionMessage.StatusCode = httpResponseMessage.StatusCode; exceptionMessage.ReasonPhrase = httpResponseMessage.ReasonPhrase; throw new HttpUnsuccessfulRequestException(exceptionMessage); } return httpResponseMessage.EnsureSuccessStatusCode(); }
public HttpUnsuccessfulRequestException(HttpExceptionMessage responseMessage) : base(responseMessage != null ? String.Format("{0}: {1}\nStatus Code: {2}", responseMessage.ReasonPhrase, responseMessage.ExceptionMessage, responseMessage.StatusCode) : null) { ResponseMessage = responseMessage; }
/// <summary> /// Determines if the HttpResponse is successful, throws otherwise. /// </summary> public static HttpResponseMessage EnsureSuccessful(this HttpResponseMessage httpResponseMessage) { // check whether it is successful status code. if not, we will attempt to read the content and // include it as part of the exception message. if (!httpResponseMessage.IsSuccessStatusCode) { HttpExceptionMessage exceptionMessage = null; try { exceptionMessage = new HttpExceptionMessage { StatusCode = httpResponseMessage.StatusCode, ReasonPhrase = httpResponseMessage.ReasonPhrase, ExceptionMessage = httpResponseMessage.Content.ReadAsStringAsync().Result, ExceptionType = typeof(HttpRequestException).Name }; } catch (Exception) { // ignore error from reading content. } if (exceptionMessage != null) { throw new HttpUnsuccessfulRequestException(exceptionMessage); } } return httpResponseMessage.EnsureSuccessStatusCode(); }