Quantcast
Channel: Web Api – no dogma blog
Viewing all articles
Browse latest Browse all 26

Letting a request fail with Polly

$
0
0

Polly is fantastic for transparently retrying a request but there is always a point at which you must give up. Here you have a choice, let the request fail and inform the original caller or use the Fallback feature of Polly. In this post I’m going to show how to let the request fail. I’ll post another time on the Polly Fallback feature.

With Polly, failing is done in much the same was as you would do without Polly. Make the request, examine the response, return the appropriate status to the caller.

The example code below shows this when calling a Web Api 2 endpoint. The hoped for response is OK (200), any other is considered a failure.

HttpResponseMessage httpResponse = await _policies.RequestTimeoutPolicy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));

if (httpResponse.IsSuccessStatusCode)
{
    int number = await httpResponse.Content.ReadAsAsync<int>();
    return Ok(number);
}

string errorMessage = await httpResponse.Content.ReadAsStringAsync();
return Content(httpResponse.StatusCode, errorMessage);

Fallback would allow me to return some default number and OK even if the web request failed. Coming soon…


Viewing all articles
Browse latest Browse all 26

Trending Articles