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
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.