Search code examples
c#exceptionrate-limitingpollyretry-logic

How to throw a custom exception in polly rate limit exceeds the rate?


I have an API that has certain limits defined. Since I have used Polly C# library to limit the calls made to API. Below is the policy I am using.

var _rateLimitPolicy = Policy.RateLimitAsync(10,TimeSpan.FromSeconds(1), 5);

var _retryPolicy = Policy
           .Handle<RateLimitRejectedException>(e => e.RetryAfter > TimeSpan.Zero)
           .WaitAndRetryAsync(
               retryCount: 3,
               sleepDurationProvider: (i, e, ctx) =>
               {
                   var rle = (RateLimitRejectedException)e;
                   return rle.RetryAfter;
               },
               onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
           );

_wrappedPolicies = Policy.WrapAsync(_retryPolicy, _rateLimitPolicy);

Currently, once the retry limit of 3 is exceeded it throws RateLimitRejectedException. I want to throw a custom error if the retry limit is exceeded. Does anyone know how to do it?


Solution

  • If you want to throw an exception then use System.Exception with an if statement

    So:

    if(retryLimit>3)
    {
        throw new System.Exception("Retry Limit exceeded 3.");
    }
    

    If you don't wish to interrupt the process with a thrown exception, you can use a try{}catch(Exception e){} too