Returning default values from a failed web request with Polly Fallbacks
Full source code available here.
Want to learn more about Polly? Check out my Pluralsight course on it.
In previous posts on Polly I showed how to use a simple retry, and a retry with a delegate that is called before the request is retried.
In this post I will show how use a Polly fallback policy, this allows a “fallback” or default value to be returned when both the request and retries fail.
The retry policy is similar to ones I have used before.
1_httpRetrytPolicy = Policy.HandleResult<HttpResponseMessage>(
2 r => r.StatusCode == HttpStatusCode.InternalServerError)
3 .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(retryAttempt));
The fallback policy returns a HttpResponseMessage
with some cached values.
1_httpRequestFallbackPolicy = Policy.HandleResult<HttpResponseMessage>(
2 r => r.StatusCode == HttpStatusCode.InternalServerError)
3 .FallbackAsync(new HttpResponseMessage(HttpStatusCode.OK)
4 {
5 Content = new ObjectContent(_cachedList.GetType(), _cachedList, new JsonMediaTypeFormatter())
6 });
Using the polices is almost the same as in my earlier posts, the httpClient.GetAsync
is executed by the retry policy. The retry policy is executed by the fallback policy. The Polly documentation refers to this as a “‘Russian-Doll’ or ‘onion-skin-layers’ model”.
1HttpResponseMessage httpResponse =
2 await _httpRequestFallbackPolicy.ExecuteAsync( ()
3 => _httpRetrytPolicy.ExecuteAsync(()
4 => httpClient.GetAsync(requestEndpoint)));
The above call inside a call can also be done with a Polly policy wrap, I will demonstrate that in later post.
If the request succeeds the first time, the response is assigned to httpResponse
. If the request fails, the retry policy kicks in and retries up to three times. If all of those fail, the fallback policy returns a httpResponse
containing the cached list.
Full source code available here.