Search code examples
c#polly

Action before retry


I have this use case where, for some errors, I need to perform an action before the retry; otherwise, just retry.

Something like this:

try
{
action:
    <action>
}
catch (SpecialException)
{
    <cleanup>
    goto action:
}
catch (Exception)
{
    goto action:
}

Is this possible with Polly?


Solution

  • register handle with Retry(Action<Exception, int> onRetry), the action will be executed before retry. so you can clear up in some case.

    Policy.Handle<Exception>().Retry((ex, count) => {
        if(ex is NotImplementedException)
        {
            Console.WriteLine("clear up");
        }
        }).Execute(() => {
            Console.WriteLine("throw exception");
            throw new Exception();//or NotImplementedException
        });