private static async Task <HttpFragileOperationResult <T> > ConvertHttpResponseMessageToHttpDeserializedResult <T>(HttpResponseMessage httpResponseMessage, JsonSerializerSettings serializerSettings = null) { var stringResult = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var statusCode = httpResponseMessage.StatusCode; if (httpResponseMessage.IsSuccessStatusCode) { try { var deserializedObject = serializerSettings == null?JsonConvert.DeserializeObject <T>(stringResult) : JsonConvert.DeserializeObject <T>(stringResult, serializerSettings); return(HttpFragileOperationResult <T> .CreateSuccessfulResult(deserializedObject, statusCode, stringResult)); } catch (JsonException e) { //Log in infrastructure Logs return(HttpFragileOperationResult <T> .CreateErrorResult(statusCode, stringResult, $"Unable to deserialize 200 result. Type: {typeof(T)}. Result: {stringResult}. Exception {e}.")); } } if ((int)statusCode >= 500) { return(HttpFragileOperationResult <T> .CreateErrorResult(statusCode, stringResult, $"500+ error result. StatusCode: {statusCode}. Response: {stringResult}")); } return(HttpFragileOperationResult <T> .CreateFailedResult(statusCode, stringResult, $"Non-500+ error result. StatusCode: {statusCode}. Response: {stringResult}")); }
public HttpFragileOperationResult <T> ToHttpFragileOperationResult <T>(IEnumerable <string> errorMessages) { switch (Status) { case Status.Error: return(HttpFragileOperationResult <T> .CreateErrorResult(StatusCode, ResponseStringContent, errorMessages.Concat(ErrorMessages))); case Status.Failed: return(HttpFragileOperationResult <T> .CreateFailedResult(StatusCode, ResponseStringContent, errorMessages.Concat(ErrorMessages))); case Status.Success: throw new ArgumentOutOfRangeException(); default: throw new ArgumentOutOfRangeException(); } }
private static async Task <HttpFragileOperationResult <T> > HttpClientExceptionHandler <T>(Func <HttpClient, Task <HttpFragileOperationResult <T> > > function, IEnumerable <KeyValuePair <string, string> > headers = null) { using (var client = new HttpClient()) { if (headers != null) { foreach (var header in headers) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } } try { return(await function(client).ConfigureAwait(false)); } catch (Exception e) { return(HttpFragileOperationResult <T> .CreateErrorResult(HttpStatusCode.InternalServerError, "", $"An exception occured while making the request. Exception: {e}")); } } }