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.

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

Here is the output.

Full source code available here.

comments powered by Disqus

Related