Search code examples
c#.netrestsharppolly

Polly retry policy outcome always successful regardless of actual response


I'm trying to take advantage of Polly's ability to handle arbitrary result conditions https://github.com/App-vNext/Polly/#step-1b-optionally-specify-return-results-you-want-to-handle.

In my test case I'm using RestSharp to make HTTP requests. Here's my sample code:

var policy = Policy
    .HandleResult<IRestResponse>(r => r.Content.Contains("bla"))
    .Retry(2)
    .ExecuteAndCapture(() =>
        {
            IRestClient client = new RestClient("https://httpbin.org/anything");
            IRestRequest request = new RestRequest(Method.GET);
            var response = client.Execute(request);
            return response;
        });

The call to https://httpbin.org/anything echos back a bunch of stuff - the exact content isn't relevant. As you can see in the predicate I'm looking for the string "bla" in the result body.

The problem is that policy.Outcome is always successful (policy.Outcome == OutcomeType.Successful) but "bla" is not in the result body.


Solution

  • The .HandleResult<TResult>(Func<TResult, bool>) clause specifies TResults you want to be considered failures - TResult values which should (in this case) trigger a retry. If "bla" is not in the result body, the result will be considered a success, a retry will not be made, and you will (expected behaviour) get .Outcome == OutcomeType.Successful.

    The following unit-test in the Polly codebase demonstrates how .ExecuteAndCapture(...) is returning OutcomeType.Failure when it should: https://github.com/App-vNext/Polly/blob/73fc38029f52d2e1bfa6f4b03bcb1e12d8c78065/src/Polly.SharedSpecs/PolicyTResultSpecs.cs#L50