Varying the Time Between Polly Retries Based on the Exception

Full source code available here.

I gave a presentation on Polly at a Meetup this week, at the end I was asked if Polly allowed the delay between retries to be determined by the exception thrown in the called code. At the time, I didn’t know if it was possible - it is, and here is the code.

The policy is below. The sleepDurationProvider takes the retry count, the exception, and the context as parameters. You could use Lambda discards if you are not going to use all the parameters, see this blog post I wrote for examples.

 1RetryPolicy waitAndRetryPolicy = Policy.Handle<Exception>()
 2    .WaitAndRetry(5,
 3    sleepDurationProvider: (retryAttempt, ex, ctx) =>
 4    {
 5        if (ex is InsufficientMemoryException)
 6        {
 7            return TimeSpan.FromSeconds(1);
 8        }
 9        else 
10        {
11            return TimeSpan.FromSeconds(2);
12        }
13    },
14    onRetry: (exception, timeSpan, retryCount, ctx) =>
15    {
16        Console.WriteLine($"Got a response of {exception.Message}, retrying {retryCount}. Delaying for {timeSpan}");
17    }
18);
 

Here is the output.

Full source code available here.

comments powered by Disqus

Related