Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Polly to retry api request if the status code is not equal to 200 OK

I am trying to use Polly to handle status codes other than 200 OK so that it retries the API request.

However, I am struggling to understand how to Polly to swallow an exception and then execute a retry. This is what I currently have, but it is not syntactically correct:

var policy = Policy.HandleResult<HttpStatusCode>(r => r == HttpStatusCode.GatewayTimeout)
                                                        .Retry(5);
        HttpWebResponse response;

        policy.Execute(() => 
        {
            response = SendRequestToInitialiseApi(url);
        });

In the execution, I need the response to also be assigned to a variable to be used elsewhere in the method.

The return type of the response is a 'HttpWebResponse' and when I get a '504' for instance, it throws an exception.

Any help/feedback would be appreciated.

like image 825
ZachOverflow Avatar asked Sep 07 '25 10:09

ZachOverflow


1 Answers

The type you provide to HandleResult must be the same type you want to return from the execution, which in your case is an HttpWebResponse since you want to make use of this value later.

Edit: I've added in exception handling as suggested by mountain traveller

var policy = Policy
    // Handle any `HttpRequestException` that occurs during execution.
    .Handle<HttpRequestException>()
    // Also consider any response that doesn't have a 200 status code to be a failure.
    .OrResult<HttpWebResponse>(r => r.StatusCode != HttpStatusCode.OK)
    .Retry(5);

// Execute the request within the retry policy and return the `HttpWebResponse`.
var response = policy.Execute(() => SendRequestToInitialiseApi(url));

// Do something with the response.
like image 89
rob.earwaker Avatar answered Sep 09 '25 01:09

rob.earwaker