Class FuncWithFallback<X,Y>
- java.lang.Object
-
- org.cactoos.func.FuncWithFallback<X,Y>
-
- Type Parameters:
X
- Type of inputY
- Type of output
- All Implemented Interfaces:
Func<X,Y>
public final class FuncWithFallback<X,Y> extends Object implements Func<X,Y>
Func with fallbacks that enable it to recover from errors.You may register several fallbacks, each for any type of exception whatsoever. If the decorated
Func
throws an exception that has an IS-A relationship with a registered fallback's exception, then that fallback's alternativeFunc
will be used to provide a result.Example scenario: you need to fetch product data from a database which may potentially not be available (SQLException). As a fallback, you then fetch the data from a local cache that is guaranteed not to fail. This is a sketch of what this code may look like:
final Product product = new FuncWithFallback<>( id -> new SqlProduct().apply(id), new Fallback.From<>( SQLException.class, id -> new CachedProduct().apply(id) ) ).apply(id);
If you register several fallback plans for exception types belonging to the same hierarchy, then the fallback plan whose exception type has the closest
InheritanceLevel
to the exception thrown will be used.Example scenario: sometimes
SqlProduct
from above will throwSQLRecoverableException
(a sub class ofSQLException
). In such cases you may want to simply retry the sameFunc
:final Product product = new FuncWithFallback<>( id -> new SqlProduct().apply(id), new IterableOf<>( new Fallback.From<>( SQLException.class, id -> new CachedProduct().apply(id) ), new Fallback.From<>( SQLRecoverableException.class, id -> new SqlProduct().apply(id) // run it again ) ) ).apply(id);
There is no thread-safety guarantee.
- Since:
- 0.2
- See Also:
ScalarWithFallback