Fallback policy with circuit breaker and retry

Polly also provides a fallback policy that returns some default responses if the service is failing. It can be used in conjunction with both the retry and circuit breaker policies. The basic idea behind fallback is to send a default response to the consumer rather than returning the actual error in the response. The response should give some meaningful information to the user that is specific to the application's nature. This is very beneficial when your services are used by external consumers of applications.

We can modify the preceding example and add fallback policies for both the retry and circuit breaker exceptions. In the ResilientHttpClient class, we will add these two variables:

static FallbackPolicy<HttpResponseMessage> _fallbackPolicy; 
static FallbackPolicy<HttpResponseMessage> _fallbackCircuitBreakerPolicy; 

Next, we add the circuit breaker policy to handle the circuit breaker exception and return the HttpResponseMessage with our custom content message. Add the following code in the parameterized constructor of the ResilientHttpClient class:

_fallbackCircuitBreakerPolicy = Policy<HttpResponseMessage> 
.Handle<BrokenCircuitException>() 
.Fallback(new HttpResponseMessage(HttpStatusCode.OK) 
  { 
    Content = new StringContent("Please try again later[Circuit breaker is Open]") 
  } 
);

Then, we will add another fallback policy, which will wrap the circuit breaker to handle any other exceptions that are not circuit breaker exceptions:

_fallbackPolicy = Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError) 
.Fallback(new HttpResponseMessage(HttpStatusCode.OK) { 
  Content = new StringContent("Some error occured") 
}); 
       

Finally, we will modify the ExecuteWithRetryandCircuitBreaker method and wrap both the retry and circuit breaker policy inside the fallback policies, which returns the general message with the 200 status code to the user:

public HttpResponseMessage ExecuteWithRetryandCircuitBreaker(string uri, Func<HttpResponseMessage> func) 
{ 
 
  PolicyWrap<HttpResponseMessage> resiliencePolicyWrap = 
Policy.Wrap(_retryPolicy, _circuitBreakerPolicy); PolicyWrap<HttpResponseMessage> fallbackPolicyWrap =
_fallbackPolicy.Wrap(_fallbackCircuitBreakerPolicy.Wrap(resiliencePolicyWrap)); var res = fallbackPolicyWrap.Execute(() => func()); return res; }

With this implementation, the user will not get any errors in response. The content contains the actual error, which is shown in the following snapshot, taken from Fiddler:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.189.5