Polly policy to log exception and rethrow

Michael Freidgeim picture Michael Freidgeim · Mar 22, 2017 · Viewed 13.5k times · Source

I consider to use Polly to create policy to log exception and rethrow. I didn't find an existing method that allow it out of the box , but some options that I see are

Fallback

// Specify a substitute value or func, calling an action (e.g. for logging)
// if the fallback is invoked.
Policy.Handle<Whatever>()
.Fallback<UserAvatar>(UserAvatar.Blank,
    onFallback: (exception, context) =>
    {
        _logger.Log(exception, context);
        throw exception;
    });

Question: is it ok to throw exception from Fallback?

Timeout

Policy.Timeout(1, T30meoutStrategy.Pessimistic,
(context, timespan, task) =>
{
    // ContinueWith important!: the abandoned task may very well still be executing,
    // when the caller times out on waiting for it!
    task.ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            logger.Error(context,t.Exception);
            throw exception;
        }
    });
}

Or Retry

Policy.Handle<DivideByZeroException>().Retry(0,
(exception, retryCount) =>
{
    logger.Error(context,exception);
    throw exception;
});

Question: is 0 retries supported?

Or KISS and write simple try/catch with throw by myself.

Which of these methods is better? What are your recommendation?

Answer

mountain traveller picture mountain traveller · Mar 25, 2017

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.