3

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.

Cheers

ZachOverflow
  • 387
  • 1
  • 3
  • 14
  • 2
    If it throws an exception instead of returning the status code, you would also likely want a `.Handle()` or `.Or()` clause in the policy (where `FooException` is the type of exception thrown). The Polly readme has examples of the `.Handle()` or `.Or()` syntax, including how to refine this to handle the exception only under certain conditions. – mountain traveller Aug 29 '19 at 17:02
  • Does this answer your question? [How to set Polly Retry for the set specific StatusCodes only](https://stackoverflow.com/questions/61019007/how-to-set-polly-retry-for-the-set-specific-statuscodes-only) – Michael Freidgeim Mar 03 '23 at 20:36

1 Answers1

3

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.
rob.earwaker
  • 1,244
  • 1
  • 7
  • 14