I'm pretty new with Polly and I'm trying to understand how works, starting from the very basics.
To test the retries I tried to create a code (Print) that has 33% to generate a DivideByZeroException
. When the error is generated it raise up to policy.Execute
seems don't managed by Polly.
Someone can help me to adjust this code? I'm using .Net Framework 4.7.2.
using System;
using Polly;
class Program
{
static void Main(string[] args)
{
var policy = Policy
.Handle<DivideByZeroException>()
.Retry();
policy.Execute(() => Print());
Console.ReadKey();
}
private static void Print()
{
var rand = new Random();
int a = rand.Next(1000, 2000);
int b = rand.Next(0, 2);
Console.WriteLine("a = {0} - b {1}", a, b);
int c = a / b;
Console.WriteLine("c = {0}", c);
}
}
If you set
b
=0
, instead of usingRandom
, you'll see it is handling the exception, but it's not retrying forever - you'll see it print output twice before failing. So it means, in the case of usingRandom
, it's sometimes settingb
to0
multiple times in a row, in which case the policy exhausts its retries, and so it throws.You can configure the policy to increase the number of retries using
Retry(n)
. Alternatively, you can useRetryForever()
.If you don't want your calling code to throw when the retries are exhausted, you can use capture the result instead: