Starting with Polly basics

590 views Asked by At

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);
    }
}
1

There are 1 answers

3
John H On

If you set b = 0, instead of using Random, 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 using Random, it's sometimes setting b to 0 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 use RetryForever().

If you don't want your calling code to throw when the retries are exhausted, you can use capture the result instead:

var result = policy.ExecuteAndCapture(() => Print());
if (result.Outcome == OutcomeType.Failure)
{
    // result.FinalException contains the exception
}