1

I'm, trying to check a simple WaitAndRetry of Polly

class Program
{
    public static void Main()
    {
           
        int i = 0;
        var _retryPolicy = Policy
       .Handle<Exception>()
        .WaitAndRetry(Backoff.ExponentialBackoff(TimeSpan.FromSeconds(2), 10),
           (exception, timespan) =>
           {
               Console.WriteLine($"Retry: {timespan}. \n ex: {exception}");
           });

        _retryPolicy.Execute(() =>
        {
            Console.WriteLine(i);
            i++;
            int.Parse("something");
        });

        Console.ReadLine();
    }
}   

And I want to throw a final exception after all the retries are failed. How can I do it?

Excepted Result:

Retry: ..

Retry: ..

Retry: ..

My new final error!

Thank You!

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
K.W
  • 123
  • 7
  • 1
    If all retry attempts failed then `Execute` will throw the last exception – Peter Csala May 11 '22 at 13:01
  • I don't understand, In the example below the Execute throw the error at each retry – K.W May 11 '22 at 13:06
  • 1
    No, it doesn't. If you run the application in a debug mode then it will stop the execution each time when the `FormatException` is thrown. But the policy handles this so the application won't crash after the first attempt. – Peter Csala May 11 '22 at 13:08
  • 1
    If you change your policy to this: `.WaitAndRetry(Backoff.ExponentialBackoff(TimeSpan.FromSeconds(2), 3), (_, timespan) => Console.WriteLine($"Retry: {timespan}."));` then it will not print the exception at each retry attempt. It will crash with an unhandled exception after 3 retry attempts. – Peter Csala May 11 '22 at 13:10

1 Answers1

2

You don't have to explicitly re-throw the last exception.

The retry works in the following way:

  • If an exception is thrown by the decorated method and there is a related .Handle<TEx> or .Or<TEx> clause inside the policy definition then it checks if the retry limit has been reached or not
    • If the retry limit has not been exceeded then it will perform yet another retry attempt
    • If the retry limit has been reached then it will throw the last exception
  • If there is not related .Handle<TEx> or .Or<TEx> clause then it will throw the last exception

Here is a diagram from the official documentation retry logic


Please also note that if you run your application in a debug mode then the IDE might stop each time when the decorated method throws exception. It depends on your IDE settings.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75