private static async Task ThrowIfFatalResponse(HttpResponseMessage response) { if (response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden || (int)response.StatusCode == 429 || // TooManyRequests response.StatusCode == HttpStatusCode.InternalServerError || response.StatusCode == HttpStatusCode.ServiceUnavailable) { // Attempt to read the error information BackblazeErrorResponse errorResponse = await response.Content.TryReadAsJsonAsync <BackblazeErrorResponse>(); if (errorResponse != null) { throw new BackblazeB2HttpException(errorResponse); } throw new BackblazeB2HttpException( "<Failed to read error content>", (int)response.StatusCode, "unknown"); } }
private async Task <HttpResponseMessage> SendRequestAsync( HttpRequestMessage request, HttpClient client) { LogRequest(request, client.BaseAddress); LogApiCallCounter(request); HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); LogResponse(response); // Check for token refresh if (response.StatusCode == HttpStatusCode.Unauthorized) { BackblazeErrorResponse errorResponse = await response.Content.TryReadAsJsonAsync <BackblazeErrorResponse>(); if (errorResponse.Code == Constants.ErrorCodes.ExpiredAuthToken || // [2018/08/09][ It appears that if the access token is old enough, it will return // a code of unauthorized instead of expired_auth_token. errorResponse.Code == "unauthorized") { // Refresh the auth token await AuthorizeAccount(); HttpRequestMessage newRequest = await request.Clone().ConfigureAwait(false); newRequest.Headers.Remove("Authorization"); newRequest.Headers.TryAddWithoutValidation( "Authorization", this.connectionInfo.AuthorizationToken.GetDecrytped()); LogRequest(newRequest, client.BaseAddress); // Dispose of the previous response before creating the new one response.Dispose(); LogApiCallCounter(newRequest); response = await client.SendAsync(newRequest).ConfigureAwait(false); LogResponse(response); } } // Any failures (including those from re-issuing after a request) will be handled here if (!response.IsSuccessStatusCode) { // Attempt to read the error information BackblazeErrorResponse errorResponse = await response.Content.TryReadAsJsonAsync <BackblazeErrorResponse>(); if (errorResponse != null) { throw new BackblazeB2HttpException(errorResponse); } throw new BackblazeB2HttpException( "<Failed to read error content>", (int)response.StatusCode, "unknown"); } return(response); }
public BackblazeB2HttpException(BackblazeErrorResponse error) : this(error.Message, error.Status, error.Code) { }