I'm trying to retry a failed operation 3 times.
I'm using Polly for a retry operation.
I want to get the exception in case the retry operation fails and retry again 2 times and so on.
return await Policy
.Handle<CustomException>()
.RetryAsync(3, onRetryAsync: async (exception, retryCount, context) =>
{
return await runner.run(params);
});
The function should return
Task<IReadOnlyCollection<string>>
I'm getting the following error:
async lambda expression converted to a task returning delegate cannot return a value
With Polly, you can define a Retry policy with the number of retries, the exponential backoff configuration, and the actions to take when there's an HTTP exception, such as logging the error. In this case, the policy is configured to try six times with an exponential retry, starting at two seconds.
Polly is a . NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, Rate-limiting and Fallback in a fluent and thread-safe manner.
I think it is unusual to run your logic in the retry policy - unless I misunderstand your question. More typically you execute the policy by calling a method that runs your logic.
Something like this:
async Task Main()
{
var polly = Policy
.Handle<Exception>()
.RetryAsync(3, (exception, retryCount, context) => Console.WriteLine($"try: {retryCount}, Exception: {exception.Message}"));
var result = await polly.ExecuteAsync(async () => await DoSomething());
Console.WriteLine(result);
}
int count = 0;
public async Task<string> DoSomething()
{
if (count < 3)
{
count++;
throw new Exception("boom");
}
return await Task.FromResult("foo");
}
output
try: 1, Exception: boom
try: 2, Exception: boom
try: 3, Exception: boom
foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With