5

I would like to perform a certain operation, and if it fails three times return null. Something like this in Polly would be perfect:

var results = await Policy<IList<Value>>
    .Handle<TaskCanceledException>()
    .RetryAsync<IList<Value>>(3)
    .FallbackAsync(null as IList<Value>)
    .ExecuteAsync(() => myRestfulCall());

This isn't possible as RetryAsync returns an AsyncRetryPolicy and there is no Fallback extension method defined on this type. Is there a Polly syntax to do this that doesn't require a try/catch block?

mountain traveller
  • 7,591
  • 33
  • 38
Aidan
  • 4,783
  • 5
  • 34
  • 58

1 Answers1

14

Polly allows you to combine any policies flexibly via PolicyWrap: extensive documentation here.

The example you quote could be achieved something like:

var fallback = Policy<IList<Value>>
    .Handle<TaskCanceledException>()
    .FallbackAsync(null as IList<Value>);

var retry = Policy<IList<Value>>
    .Handle<TaskCanceledException>()
    .RetryAsync<IList<Value>>(3);

var results = await fallback.WrapAsync(retry)
    .ExecuteAsync(() => myRestfulCall());
mountain traveller
  • 7,591
  • 33
  • 38
  • 1
    I think you missed an `await` before the call to `WrapAsync`, but thank you that's exactly what I was missing. – Aidan Mar 25 '19 at 09:08