In this article, we are going to present the Fallback policy available in Failsafe library. Fallbacks allow you to provide an alternative result for a failed execution.
2. Basic use
The most basic use is to set a default result object of any kind as a fallback:
We could also throw a new custom exception:
Or compute an alternative result such as from a backup resource:
A CompletionStage can be supplied as a fallback:
And for computations that block, a Fallback can be configured to run asynchronously:
3. Event listeners
Fallbacks support event listeners that can tell you when an execution attempt failed:
4. JUnit test
The following JUnit test makes the use of the Fallback policy. We set the fallback to another object. When an error occurs Failsafe library will choose an alternative result object:
5. Conclusion
This article shows the simplest way to use the Fallback policy using Failsafe library. Fallback allows us to give an alternative result if execution failed.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}