Polly policy to log exception and rethrow

If you do not already have Polly in the mix, try/catch would seem simplest.

If you already have Polly in the mix, FallbackPolicy can safely be re-purposed in the way you suggest. The onFallback delegate and fallback action or value are not governed by the .Handle<>() clauses of the Policy, so you can safely rethrow an exception from within the onFallback delegate.

Policy<UserAvatar>.Handle<Whatever>()
.Fallback<UserAvatar>(UserAvatar.Blank,
    onFallback: (exception, context) =>
    {
        _logger.Log(exception, context);
        throw exception;
    });

The approach your question outlines with TimeoutPolicy would only capture exceptions thrown by delegates the caller had earlier walked away from due to timeout, and only in TimeoutMode.Pessimistic; not all exceptions.


The approach your question outlines with .Retry(0, ...) would not work. If no retries are specified, the onRetry delegate would not be invoked.


To avoid the untidiness of repurposing FallbackPolicy, you could also code your own LogThenRethrowPolicy, within Polly's structures. This commit (which added the simple NoOpPolicy) exemplifies the minimum necessary to add a new policy. You could add an implementation similar to NoOpPolicy but just try { } catch { /* log; rethrow */ }


EDIT January 2019: Polly.Contrib now also contains a Polly.Contrib.LoggingPolicy which can help with this.


https://github.com/App-vNext/Polly-Samples/blob/master/PollyDemos/Async/AsyncDemo02_WaitAndRetryNTimes.cs shows that you can use the onRetry: option, at least for WaitAndRetryAsync. I haven't looked at the others yet.

HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3,
    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))  // exponential back-off: 2, 4, 8 etc
                    + TimeSpan.FromMilliseconds(Jitterer.Next(0, 1000)), // plus some jitter: up to 1 second
    onRetry: (response, calculatedWaitDuration) =>
    {
        logger.LogError($"Failed attempt. Waited for {calculatedWaitDuration}. Retrying. {response.Exception.Message} - {response.Exception.StackTrace}");
    }
);