Search code examples
c#ooppolly

Wrapper around Polly library so that implementation can stay at a single place


I have gone through the documentation and examples of Polly library, and it's really awesome and simple to use !!

In my case, I want to classify all the exceptions into 3 types: temporary, permanent and log. Now, I want to have a single piece of code which will be responsible to handle errors which are temporary in nature by doing wait and retry using Polly library.

  WaitAndRetryAsync(new[]{
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(5)
                  })

Same way, if something is permanent in nature (should be able to know it's type based on the exception we are trying to handle example: timeout can be interim but if database cred are not correct then it's permanent) then we can send email to the support staff.

Now, the problem starts here that, how I can wrap it using an interface or Abstract class so that my all the derived class can pass on an exception along with method name, which can be passed on to my new framework and it will do the needful.

Any pointers will be of great help !


Solution

  • You could create a class that accepts a Func or Action to the code you want Polly to call.

    Something like this helper method:

    public class RetryWrapper
        {
            public static TOutput Execute<TInput, TOutput>(Func<TInput, TOutput> func, TInput input)
            {
                RetryPolicy retryPolicy = Policy.Handle<TimeoutException>()
                    .Or<OtherException>()
                    .WaitAndRetry(3, x => new TimeSpan(0, 0, 2));
    
                return retryPolicy.Execute(() => func(input));
            }
        }
    

    Then you can call it

    var result = RetryWrapper.Execute<string, bool>(x => MethodToCall(x), "input")