Polly politicizing to register exceptions and retruns
I consider using Polly to create a policy for logging exceptions and retroning. I didn't find an existing method that allows this out of the box, but some of the options I see are
Renouncement
// Specify a substitute value or func, calling an action (eg for logging) if the fallback is invoked.
Policy.Handle<Whatever>()
.Fallback<UserAvatar>(UserAvatar.Blank, onFallback: (exception, context) =>
{ _logger.Log(exception, context);
throw exception;
});
Question: can an exception be thrown from Fallback?
Timeout
Policy.Timeout(1, T30meoutStrategy.Pessimistic, (context, timespan, task) =>
{ task.ContinueWith(t =>
{ // ContinueWith important!: the abandoned task may very well still be executing, when the caller times out on waiting for it!
if (t.IsFaulted )
{
logger.Error(context,t.Exception);
throw exception;
} );
Or Repeat
Policy.Handle<DivideByZeroException>().Retry(0, (exception, retryCount) =>
{ logger.Error(context,exception);
throw exception;
} );
Question: are 0 attempts supported?
Or KISS and write a simple try / catch with a throw.
Which of these methods is better? What are your recommendations?
source to share
If you don't already have Polly in your mix, try / catch will seem simple.
If you already have Polly in the mix, FallbackPolicy
you can safely reassign the way you suggest. The delegate onFallback
and fallback action or value is not governed by the .Handle<>()
policy clauses , so you can safely throw the exception from within the delegate onFallback
.
Policy<UserAvatar>.Handle<Whatever>()
.Fallback<UserAvatar>(UserAvatar.Blank, onFallback: (exception, context) =>
{ _logger.Log(exception, context);
throw exception;
});
The approach you ask with TimeoutPolicy
will only catch exceptions that were thrown by delegates that were previously timed out, and only in TimeoutMode.Pessimistic
; not all exceptions.
The approach your question outlines with .Retry(0, ...)
will not work. If no retries are specified, the delegate onRetry
will not be called.
To avoid fuzzy duplicate copying FallbackPolicy
, you can also create your own LogThenRethrowPolicy
code inside Polly structures. This commit (with a simple one added NoOpPolicy
) illustrates the minimum required to add a new policy. You can add an implementation similar to NoOpPolicy
but simplytry { } catch { /* log; rethrow */ }
source to share