private static async Task CheckForFaultedResponses(HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { Error error = null; try { error = RestClientHelper.DeserializeObject <Error>(responseStream); } catch { // ignored } if (error == null) { error = new Error(string.Format("Request {0} {1} was not successful: {2} ({3})", response.RequestMessage.Method, response.RequestMessage.RequestUri, (int)response.StatusCode, response.ReasonPhrase)); } throw new WrappedServerErrorException(error, response.StatusCode); } }
private static async Task <T> ResponseToObjectAsync <T>(HttpResponseMessage response) { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return(RestClientHelper.DeserializeObject <T>(responseStream)); } }
private async Task <T> GetResponse <T>(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { try { using (var response = await _HttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false)) { await CheckForFaultedResponses(response).ConfigureAwait(false); using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return(RestClientHelper.DeserializeObject <T>(responseStream)); } } } catch (HttpRequestException e) { throw new RestClientException(string.Format("Error fetching web service response for request [{0}]: {1}", request.RequestUri, e.Message), e); } }
/// <summary> /// Handles all responses with status codes between 400 and 499 /// </summary> private static async Task HandleClientBasedFaults(HttpResponseMessage response) { if (response.StatusCode < HttpStatusCode.BadRequest || response.StatusCode >= HttpStatusCode.InternalServerError) { return; } using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { Error error; try { error = RestClientHelper.DeserializeObject <Error>(responseStream); if (error == null) { error = new Error($"Request {response.RequestMessage.Method} {response.RequestMessage.RequestUri} was not successful: {( int ) response.StatusCode} ({response.ReasonPhrase})"); } } catch (JsonReaderException) { var buffer = (responseStream as MemoryStream)?.ToArray(); var content = buffer != null?Encoding.UTF8.GetString(buffer) : null; error = new Error($"Request {response.RequestMessage.Method} {response.RequestMessage.RequestUri} was not successful: {( int ) response.StatusCode} ({response.ReasonPhrase})") { ExceptionMessage = content, }; } catch (Exception) { error = new Error($"Request {response.RequestMessage.Method} {response.RequestMessage.RequestUri} was not successful: {( int ) response.StatusCode} ({response.ReasonPhrase})"); } throw new WrappedServerErrorException(error, response); } }