Polly-Samples
Polly-Samples copied to clipboard
Exception not re-thrown
In the following code the inner method InvokeAsync is throwing an OnlineException but I can never catch it what is re-thrown is a simple Exception:
//-- in a singleton
CircuitBreakerPolicy = Policy
.Handle<Exception>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: ExceptionsAllowedForCircuiteBreaker,
durationOfBreak: TimeSpan.FromSeconds(BreakTime),
onBreak: (ex, breakDelay) =>
{
Debug.Log($".Breaker logging: Breaking the circuit for {breakDelay.TotalMilliseconds} ms!");
Debug.Log($"..due to: + {ex.Message}");
},
onReset: () => Debug.Log(".Breaker logging: Call ok! Closed the circuit again!"),
onHalfOpen: () => Debug.Log(".Breaker logging: Half-open: Next call is a trial!")
);
//--
public virtual async Task<IOnlineResponse> Process(CancellationToken ct)
{
Debug.Log($"Processing = {Type}");
State = new RequestState();
U serviceResponse = null;
AsyncTimeoutPolicy timeoutPolicy = Policy.TimeoutAsync(TimeOut);
AsyncRetryPolicy waitAndRetryPolicy = Policy
.Handle<Exception>(e => !(e is BrokenCircuitException))
.WaitAndRetryAsync(
retryCount: DefaultRetryCount,
attempt => TimeSpan.FromMilliseconds(AttemptDelay),
(exception, calculatedWaitDuration) =>
{
Debug.Log($".Request exception (will retry): " + exception.Message);
});
AsyncPolicyWrap policyWrap = Policy.WrapAsync(timeoutPolicy, waitAndRetryPolicy, CircuitBreaker.Instance.CircuitBreakerPolicy);
try
{
serviceResponse = await policyWrap.ExecuteAsync(async (cancellationToken) =>
{
await CheckConnectivity(cancellationToken);
return await InvokeAsync(cancellationToken);
}, ct, continueOnCapturedContext: true);
State.Status = RequestStatus.Success;
State.Message = "";
}
catch (OnlineException ex)
{
State.Status = OnlineExceptionStatusToRequestStatus(ex.StatusCode);
State.Message = ex.ToString();
}
catch (Exception ex)
{
State.Status = RequestStatus.Failed;
State.Message = ex.ToString();
}
Debug.Log($"Response = {Type} - {State.Status}");
return new V { State = State, Response = serviceResponse };
}
Never mind its a simple fix I added the custom exception to both CB and Retry policies (hopefully I'm doing it right):
CircuitBreakerPolicy = Policy
.Handle<OnlineException>()
.Or<Exception>()
AsyncRetryPolicy waitAndRetryPolicy = Policy
.Handle<OnlineException>()
.Or<Exception>(e => !(e is BrokenCircuitException))