Question
Migration from Polly to Microsoft.Extensions.Http.Resilience - Extend ShouldHandle
I want to migrate from Polly to the Microsoft.Extensions.Http.Resilience
AddStandardResilienceHandler
. My shortened Polly code is the following:
services.AddHttpClient<MyService>()
.AddPolicyHandler((_, _) =>
{
return HttpPolicyExtensions.HandleTransientHttpError()
.Or<HttpRequestException>(exception => exception.StatusCode == HttpStatusCode.Conflict)
.WaitAndRetryAsync(3, sleepDurationProvider: i => TimeSpan.FromSeconds(i * 2));
});
The crucial part here is HttpPolicyExtensions.HandleTransientHttpError().Or<HttpRequestException>(exception => exception.StatusCode == HttpStatusCode.Conflict)
where I want to add a custom error case in which I want to do a retry.
I do not really know how to convert this into the new configuration.
As far as I understand the docs I can set a custom options.Retry.ShouldHandle
function (Gets or sets a predicate that determines whether the retry should be executed for a given outcome.)
But then I cannot add a case rather than I have to set the whole function. Microsofts default implementation of ShouldHandle
looks like this:
public static readonly Func<TArgs, ValueTask<bool>> HandleOutcome = args => args.Outcome.Exception switch
{
OperationCanceledException => PredicateResult.False(),
Exception => PredicateResult.True(),
_ => PredicateResult.False()
};
My current config looks like this:
services.AddHttpClient<MyService>()
.AddStandardResilienceHandler()
.Configure((options, _) =>
{
options.Retry.ShouldHandle = args =>
{
if (args.Outcome.Result?.StatusCode == HttpStatusCode.Conflict)
{
return PredicateResult.True();
}
return args.Outcome.Exception switch
{
OperationCanceledException => PredicateResult.False(),
not null => PredicateResult.True(),
_ => PredicateResult.False()
};
};
});
Is this equivalent to the initial Polly implementation?