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:
ArgumentException
s (includingArgumentNullException
andArgumentOutOfRangeException
) as handled exception.ArgumentException
and in case ofNotSupportedException
as well.So, from the Circuit Breaker perspective if a
NotSupportedException
is thrown than it will not be considered >> hence the name unhandled.This is how our sample method is implemented which will either throw an
ArgumentException
or aNotSupportedException
:The usage of the policies:
Output when
threshold
is set to 3After the CB has been transferred itself into the
HalfOpen
state then theSampleCall
throws onlyNotSupportedException
s. This is not handled by the CB that's why it remains in theHalfOpen
state.Output when
threshold
is 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
threshold
is set to 4Because the
SampleCall
did throwArgumentException
when the CB was in theHalfOpen
state that's why CB considered that as handled exception and transferred itself fromHalfOpen
toOpen
.