In this article, we will cover failsafe policies responsible for determining which execution results or failures to handle. By default, all thrown exceptions will be handled. Failsafe is a flexible API that allows us to handle also more specific errors under specified conditions.
In case you want to read more about failsafe, check getting started with Failsafe library post.
2. Failsafe policies
Failsafe supports four kinds of policies:
- Retry - express when retries should be performed for an execution,
- Timeout - allows failing an execution with
TimeoutExceededExceptionif it takes too long to complete,
- Fallback - allows providing an alternative result for a failed execution,
- Circuit Breaker - allows creating systems that fail fast by temporarily disabling execution as a way of preventing system overload.
3. Policies composition
Failsafe policies can be composed in many different ways. We can also create multiple policies of the same type.
The following code shows the use of typical policies composition:
In this example
supplier is evaluated first, then it’s result is handled by the
Timeout, then the
RetryPolicy, and the
Each policy makes its own determination as to whether the result represents a failure. This allows different policies to be used for handling different types of failures.
4. Handling specific failures or conditions
Policies can also be configured to handle more specific failures or conditions:
They can also be configured to handle specific results or result conditions:
In this short article, we presented failsafe policies that determine which execution results or failures to handle and how to handle them. We showed that policies could be handled conditionally and can be composed in many ways.