Reputation: 59
Iam using Polly retry policy to retry while throwing exception.Here Iam trying to use that retry policy inside a loop.So while executing the foreach loop if it throws any exception then Polly retries.This part works fine.But i want to continue with the next iteration inside the loop after retry.But it throws final exception after 2 retries and returns to calling method.
static void Main(string[] args)
{
RetryPolicy();
}
private static void RetryPolicy()
{
try
{
var retryPolicy = Policy.Handle<Exception>().Retry(2);
List<int> list = new List<int>();
list.AddRange(new int[] { 0, 1, 2, 3, 4 });
foreach(var item in list)
{
retryPolicy.Execute(() => Calculate(item));
}
}
catch (Exception ex)
{
}
}
private static void Calculate(int j)
{
int a = 10;
int b = j;
var c = a / b;
}
Here in first iteration it gives error and after 2 retries i want to return to the loop and continue with other items inside for each loop.Is there any way i can achieve this with Polly. Please suggest.
Upvotes: 0
Views: 1501
Reputation: 2540
Your try/catch
is in the wrong place - it should be inside the loop. That way, when Polly throws an exception after the final retry, the exception is caught and handled (please don't use empty catches), then the loop continues.
But there's an even better way: remove the try/catch and use ExecuteAndCapture() - this returns a result that indicates whether there was an overall success or failure. Then do something with it:
private static void RetryPolicy()
{
var retryPolicy = Policy.Handle<Exception>().Retry(2);
List<int> list = new List<int>();
list.AddRange(new int[] { 0, 1, 2, 3, 4 });
foreach(var item in list)
{
var policyResult = retryPolicy.ExecuteAndCapture(() => Calculate(item));
if (policyResult.Outcome != OutcomeType.Successful)
{
// do something remedial. then the loop can continue.
}
}
}
Upvotes: 2