1

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?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Kavin404
  • 959
  • 2
  • 11
  • 18

2 Answers2

1

Whenever you want to execute your _wrappedPolicies
then you can call either ExecuteAsync or ExecuteAndCaptureAsync methods.

PolicyResult policyExecutionResult = await _wrappedPolicies.ExecuteAndCaptureAsync(...);

On this result object there is a property called FinalException. You can examine that and based on the assessment result you can throw a custom exception

if (policyExecutionResult.FinalExecption is RateLimitRejectedException)
   throw new CustomException(...);
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
0

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

Display name
  • 413
  • 3
  • 14
  • Sorry, I am a bit new to this. From where do I get the retry limit? – Kavin404 Dec 30 '22 at 04:50
  • If you are not tracking the retry limit somewhere then a `try{}catch(Exception e){}` where you throw your own exception will probably be your best bet. – Display name Dec 30 '22 at 05:27