X
- Type of inputY
- Type of outputpublic final class FuncWithFallback<X,Y> extends Object implements Func<X,Y>
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 alternative Func
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 FallbackFrom<>(
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 throw SQLRecoverableException
(a sub class of
SQLException
). In such cases you may want to simply retry the same
Func
:
final Product product = new FuncWithFallback<>(
id -> new SqlProduct().apply(id),
new IterableOf<>(
new FallbackFrom<>(
SQLException.class,
id -> new CachedProduct().apply(id)
),
new FallbackFrom<>(
SQLRecoverableException.class,
id -> new SqlProduct().apply(id) // run it again
)
)
).apply(id);
There is no thread-safety guarantee.
ScalarWithFallback
Func.NoNulls<X,Y>
Constructor and Description |
---|
FuncWithFallback(Func<X,Y> fnc,
FallbackFrom<Y> fbk)
Ctor.
|
FuncWithFallback(Func<X,Y> fnc,
Iterable<FallbackFrom<Y>> fbks)
Ctor.
|
public FuncWithFallback(Func<X,Y> fnc, FallbackFrom<Y> fbk)
fnc
- The funcfbk
- The fallbackCopyright © 2017–2019 Cactoos. All rights reserved.