Letting a request fail with Polly

Want to learn more about Polly? Check out my Pluralsight course on it.

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.

 1HttpResponseMessage httpResponse = await _policies.RequestTimeoutPolicy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));
 2
 3if (httpResponse.IsSuccessStatusCode)
 4{
 5    int number = await httpResponse.Content.ReadAsAsync<int>();
 6    return Ok(number);
 7}
 8
 9string errorMessage = await httpResponse.Content.ReadAsStringAsync();
10return Content(httpResponse.StatusCode, errorMessage);

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

comments powered by Disqus

Related