/** * Extract an {@link ErrorCodes} response from the error object encoded in an {@link * HttpResponseException}. * * @param httpResponseException the response exception * @return the parsed {@link ErrorCodes} if found * @throws HttpResponseException rethrows the original exception if an error object could not be * parsed, if there were multiple error objects, or if the error code is unknown. */ public static async Task <ErrorCode> GetErrorCodeAsync(HttpResponseMessage httpResponse) { httpResponse = httpResponse ?? throw new ArgumentNullException(nameof(httpResponse)); // Obtain the error response code. string errorContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); if (errorContent == null) { throw new HttpResponseException(httpResponse); } try { ErrorResponseTemplate errorResponse = JsonTemplateMapper.ReadJson <ErrorResponseTemplate>(errorContent); IReadOnlyList <ErrorEntryTemplate> errors = errorResponse?.Errors; // There may be multiple error objects if (errors?.Count == 1) { var errorCode = errors[0].Code; // May not get an error code back. if (errorCode.HasValue) { return(errorCode.GetValueOrDefault()); } } } catch (Exception e) when(e is IOException || e is ArgumentException) { // Parse exception: either isn't an error object or unknown error code } // rethrow the original exception throw new HttpResponseException(httpResponse); }
public async Task TestHandleHttpResponseExceptionAsync() { ErrorResponseTemplate emptyErrorResponseTemplate = new ErrorResponseTemplate() .AddError(new ErrorEntryTemplate(ErrorCode.BlobUnknown, "some message")); using (HttpResponseMessage mockHttpResponseException = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(JsonTemplateMapper.ToUtf8String(emptyErrorResponseTemplate)) }) { bool result = await testBlobChecker.HandleHttpResponseExceptionAsync(mockHttpResponseException).ConfigureAwait(false); Assert.IsFalse(result); } }
public async Task TestHandleHttpResponseException_notBlobUnknownAsync() { ErrorResponseTemplate emptyErrorResponseTemplate = new ErrorResponseTemplate(); using (HttpResponseMessage mockHttpResponseException = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(JsonTemplateMapper.ToUtf8String(emptyErrorResponseTemplate)) }) { try { await testBlobChecker.HandleHttpResponseExceptionAsync(mockHttpResponseException).ConfigureAwait(false); Assert.Fail("Non-BLOB_UNKNOWN errors should not be handled"); } catch (HttpResponseException ex) { Assert.AreEqual(mockHttpResponseException, ex.Cause); } } }