Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polly final action after max retry

The C# project that I'm working on uses Polly (v8.3) for resiliency. The code looks very much similar to the sample found in the Github documentation :

ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions{/*omitted*/})
    .Build();

and subsequently

pipeline.Execute(() => SomeVoidMethodThatMayFail());

The retry options have been omitted here, it boils down to that Polly will retry 5 times and on every failed attempt an entry is written to a log. As can be deduced from the use of a non-generic RetryStrategyOptions, the code that may throw an exception has a return type of void.

The last thing that I need to implement, is a 'finally'-block, e.g. send an email if the retries have been exhausted. I thought of using a fallback, but there is no non-generic FallbackStrategyOptions. What would be the appropriate Polly-way to execute code after the last retry has failed? Of course, I could change my method to return e.g. bool instead of void, but that seems like a work around

like image 924
SimonAx Avatar asked Nov 19 '25 15:11

SimonAx


1 Answers

If the strategy has exhausted all the retry attempts then it will throw the last exception. So, you need a catch block, not a finally

try
{
   pipeline.Execute(() => SomeVoidMethodThatMayFail());
   // The pipeline has succeeded without exhausting all retry attempts
}
catch(Exception ex) // The same exception type(s) as you have in your ShouldHandle
{
   // The pipeline has failed by exhausting all retry attempts
}

There is an API called ExecuteOutcomeAsync which is considered the successor of the ExecuteAndCapture{Async} safe methods. At the time of writing, it has only async API and your to-be-decorated method should return a ValueTask<Outcome<TResult>> which is not suitable for your use case.

like image 161
Peter Csala Avatar answered Nov 21 '25 04:11

Peter Csala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!