Polly Retries and Exceptions in .Net 6

December 3, 2021    Development .Net

Polly Retries and Exceptions in .Net 6

I needed to clear up my understanding about Polly, retries and exception. I like how clean this console app in .Net 6 is.

I answered a question on StackOverflow in November, 2018.

using Polly;

var retry = Policy
            .Handle<Exception>()
            .WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            onRetry: (exception, calculatedWaitDuration) =>
            {
                Console.WriteLine($"Failed attempt. Waited for {calculatedWaitDuration}. Retrying. {exception.Message}. {exception.ToString()}");
            });

try
{
    var count = 1;
    retry.Execute(() =>
    {
        Console.WriteLine("start");
        Console.WriteLine("Hello, World!");
        if (true)// count == 1)
        {         
            count++;
            throw new Exception("Boom!");
        }
        Console.WriteLine("end");
    });

}
catch (Exception)
{
    Console.WriteLine("Catch");
    throw;
}

Here’s the output in the console:

start
Hello, World!
Failed attempt. Waited for 00:00:02. Retrying. Boom!. System.Exception: Boom!
   at Program.<>c__DisplayClass0_0.<<Main>$>b__2() in c:\chr\PollyTest\Program.cs:line 21
   at Polly.Policy.<>c__DisplayClass108_0.<Execute>b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.<>c__DisplayClass138_0.<Implementation>b__0(Context ctx, CancellationToken token)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
start
Hello, World!
Failed attempt. Waited for 00:00:04. Retrying. Boom!. System.Exception: Boom!
   at Program.<>c__DisplayClass0_0.<<Main>$>b__2() in c:\chr\PollyTest\Program.cs:line 21
   at Polly.Policy.<>c__DisplayClass108_0.<Execute>b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.<>c__DisplayClass138_0.<Implementation>b__0(Context ctx, CancellationToken token)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
start
Hello, World!
Catch
Unhandled exception. System.Exception: Boom!
   at Program.<>c__DisplayClass0_0.<<Main>$>b__2() in c:\chr\PollyTest\Program.cs:line 21
   at Polly.Policy.<>c__DisplayClass108_0.<Execute>b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.<>c__DisplayClass138_0.<Implementation>b__0(Context ctx, CancellationToken token)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates`1 shouldRetryResultPredicates, Action`4 onRetry, Int32 permittedRetryCount, IEnumerable`1 sleepDurationsEnumerable, Func`4 sleepDurationProvider)
   at Polly.Retry.RetryPolicy.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken)
   at Polly.Policy.Implementation(Action`2 action, Context context, CancellationToken cancellationToken)
   at Polly.Policy.Execute(Action`2 action, Context context, CancellationToken cancellationToken)
   at Polly.Policy.Execute(Action action)
   at Program.<Main>$(String[] args) in c:\chr\PollyTest\Program.cs:line 14

c:\chr\PollyTest\bin\Debug\net6.0\PollyTest.exe (process 18660) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

https://github.com/App-vNext/Polly-Samples/blob/master/PollyDemos/Async/AsyncDemo02_WaitAndRetryNTimes.cs

Update with .Net 8

I encourage you to watch (Building resilient cloud services with .NET 8 | .NET Conf 2023)[https://www.youtube.com/watch?v=BDZpuFI8mMM&list=PLdo4fOcmZ0oULyHSPBx-tQzePOYlhvrAU&index=14] and look into version 8