FallbackPolicy
using Polly.Utilities;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Polly.Fallback
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class FallbackPolicy : Policy, IFallbackPolicy, IsPolicy
{
private Action<Exception, Context> _onFallback;
private Action<Exception, Context, CancellationToken> _fallbackAction;
internal FallbackPolicy(PolicyBuilder policyBuilder, Action<Exception, Context> onFallback, Action<Exception, Context, CancellationToken> fallbackAction)
: base(policyBuilder)
{
if (onFallback == null)
throw new ArgumentNullException("onFallback");
_onFallback = onFallback;
if (fallbackAction == null)
throw new ArgumentNullException("fallbackAction");
_fallbackAction = fallbackAction;
}
[DebuggerStepThrough]
protected override void Implementation(Action<Context, CancellationToken> action, Context context, CancellationToken cancellationToken)
{
FallbackEngine.Implementation(delegate(Context ctx, CancellationToken token) {
action(ctx, token);
return EmptyStruct.Instance;
}, context, cancellationToken, base.ExceptionPredicates, ResultPredicates<EmptyStruct>.None, delegate(DelegateResult<EmptyStruct> outcome, Context ctx) {
_onFallback(outcome.Exception, ctx);
}, delegate(DelegateResult<EmptyStruct> outcome, Context ctx, CancellationToken ct) {
_fallbackAction(outcome.Exception, ctx, ct);
return EmptyStruct.Instance;
});
}
protected override TResult Implementation<[System.Runtime.CompilerServices.Nullable(0)] TResult>(Func<Context, CancellationToken, TResult> action, Context context, CancellationToken cancellationToken)
{
throw new InvalidOperationException("You have executed the generic .Execute<TResult> method on a non-generic FallbackPolicy. A non-generic FallbackPolicy only defines a fallback action which returns void; it can never return a substitute TResult value. To use FallbackPolicy to provide fallback TResult values you must define a generic fallback policy FallbackPolicy<TResult>. For example, define the policy as Policy<TResult>.Handle<Whatever>.Fallback<TResult>(/* some TResult value or Func<..., TResult> */);");
}
}
}