Letting a request fail with Polly

Datetime:2017-04-20 05:22:25         Topic: .Net          Share        Original >>
Here to See The Original Article!!!

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 all me to return some default number and OK even if the web request failed. Coming soon…