I want to use Polly to implement a Circuit Breaker pattern.
In the docs, there is a description of the Half Open state, and there it says:
- If a handled exception is received, that exception is rethrown, and the circuit transitions immediately back to open, and remains open again for the configured timespan.
- If an unhandled exception is received, the circuit remains in half-open.
I'm not sure I understand the difference here between handled and unhandled exception. We are describing a case where an action is run by the policy and is throwing an exception.
When they say the exception is handled, where do they mean it's being handled? because as we said, the action threw it so doesn't it mean it's unhandled?
It makes me not understand completely when the half open state remains half open and when does it transition to open.
When you define a Circuit Breaker policy then you can define what sort of exception(s) should be considered by the CB implementation. In other words you can list those exceptions that should be treated as failed execution and should be counted into the successive failure count.
You can define the list of exceptions with the combination of
Handle<T>andOr<T>method calls.Let's scrutinize this concept via a simple example:
ArgumentExceptions (includingArgumentNullExceptionandArgumentOutOfRangeException) as handled exception.ArgumentExceptionand in case ofNotSupportedExceptionas well.So, from the Circuit Breaker perspective if a
NotSupportedExceptionis thrown than it will not be considered >> hence the name unhandled.This is how our sample method is implemented which will either throw an
ArgumentExceptionor aNotSupportedException:The usage of the policies:
Output when
thresholdis set to 3After the CB has been transferred itself into the
HalfOpenstate then theSampleCallthrows onlyNotSupportedExceptions. This is not handled by the CB that's why it remains in theHalfOpenstate.Output when
thresholdis set to 2The CB did not break because there was no two successive
ArgumentException. But the retry did trigger because it also handlesNotSupportedException.Output when
thresholdis set to 4Because the
SampleCalldid throwArgumentExceptionwhen the CB was in theHalfOpenstate that's why CB considered that as handled exception and transferred itself fromHalfOpentoOpen.