Sunday, May 16, 2021

Polly: Executing an Action with Retries

In this post, let's have a look at how we can execute any Actions with Retries using Polly. It's actually quite easy.

Rather than explaining in words, a code sample would greatly explain itself.

Say I have this custom exception, so whenever I received this exception, let's say I want to add some retry logic.

public class MyCustomException : Exception
{
    public MyCustomException(string message) : base(message)
    {
    }
}

So I can create a Retry Policy and just execute whatever our action within the policy. (here I am just using the async counterpart since that what we are using almost all the time). 

using Microsoft.Extensions.Logging;
using Polly;
using Polly.Retry;
using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddConsole();
            });

            ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

            AsyncRetryPolicy policy = CreatePolicyFor<MyCustomException>(logger);

            await policy.ExecuteAsync(async () =>
            {
                await DoSomething();
            });
        }

        private static async Task DoSomething()
        {
            throw new MyCustomException("Some Exception");
        }

        private static AsyncRetryPolicy CreatePolicyFor<TException>(ILogger loggerint retries = 3, int delayInSecods = 5)  where TException : Exception
        {
            return Policy
                .Handle<TException>()
                .WaitAndRetryAsync(
                    retryCount: retries,
                    sleepDurationProvider: retry => TimeSpan.FromSeconds(delayInSecods),
                    onRetry: (exceptiontimeSpanretryctx) =>
                    {
                        logger.LogWarning(exception,
                            "Exception {ExceptionType} with message {Message} detected on attempt {retry} of {retries}",
                            exception.GetType().Name,
                            exception.Message,
                            retry,
                            retries);
                    }
                );
        }
    }
}

We can specify how many retries we want, the sleep duration between retries, and nicely, we can even specify an Action to be executed when retrying (like I am logging the attempt info here).

Hope this helps!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment