Package io.reacted.patterns
Class Try<T>
java.lang.Object
io.reacted.patterns.Try<T>
- Direct Known Subclasses:
Try.Failure,Try.Success
public abstract class Try<T>
extends java.lang.Object
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classTry.Failure<T>static classTry.Success<T>static interfaceTry.TryConsumer<T>static interfaceTry.TryMapper<T,R>static interfaceTry.TryResourceSupplier<T>static interfaceTry.TryValueSupplier<T> -
Field Summary
-
Method Summary
Modifier and Type Method Description Try<T>filter(UnChecked.CheckedPredicate<? super T> predicate)If the Try is a failure, the current Try is returned.Try<T>filter(UnChecked.CheckedPredicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> exceptionOnTestFailure)If the Try is a failure, the current Try is returned.<U> Try<U>flatMap(Try.TryMapper<? super T,Try<? extends U>> flatMapper)Like Stream.flatMap(), Try.flatMap flattens two nested Try.abstract Tget()This get will return the success value of a successful Try.abstract java.lang.ThrowablegetCause()static <U> Try<U>identity(Try<U> value)Identity Try function.static <U> Uidentity(U value)Identity function.Try<java.lang.Void>ifError(Try.TryConsumer<? super java.lang.Throwable> consumer)If Try is a failure, the provided consumer will be applied to the generated Throwable.Try<java.lang.Void>ifSuccess(Try.TryConsumer<? super T> consumer)If the Try is a success, the provided consumer is applied to the result.Try<java.lang.Void>ifSuccessOrElse(Try.TryConsumer<? super T> successConsumer, Try.TryConsumer<? super java.lang.Throwable> failureConsumer)A functional if then else: if the Try is successful the successConsumer is used, otherwise the throwable consumer.booleanisFailure()abstract booleanisSuccess()<U> Try<U>map(Try.TryMapper<? super T,? extends U> mapper)If the Try is successful, another Try will be returned with the result of the specified mapper, otherwise the current Try is returned<U> Try<U>mapOrElse(Try.TryMapper<? super T,? extends U> ifSuccess, Try.TryMapper<? super java.lang.Throwable,? extends U> orElse)A functional if then else: if the Try is successful the ifSuccess mapper is used, otherwise the throwable mapper.static java.lang.VoidnoOp(java.lang.Object... args)Placeholder for a no operationstatic <T> Try<T>of(Try.TryValueSupplier<? extends T> supplier)Creates a Try monad with the result of a computationstatic <T> Try<T>ofCallable(UnChecked.CheckedCallable<? extends T> function)static <T> Try.Failure<T>ofFailure(java.lang.Throwable throwable)Creates a failed Try carrying the specified failure exceptionstatic Try<java.lang.Void>ofRunnable(UnChecked.CheckedRunnable function)static <T> Try.Success<T>ofSuccess(T value)Creates a successful Try carrying the specified valuedTorElse(T alternative, java.util.function.Consumer<? super java.lang.Throwable> exceptionConsumer)Gets the value contained in Try on success, otherwise returns the specified value and the exception that generated the failure is processed with the provided consumer<U extends T>
TorElse(U alternative)Gets the value contained in Try on success, otherwise returns the specified value.TorElseGet(java.util.function.Function<? super java.lang.Throwable,? extends T> exceptionMapper)TorElseGet(java.util.function.Supplier<? extends T> alternative)Gets the value contained in Try on success, otherwise returns the output of the provided supplier.TorElseGet(java.util.function.Supplier<? extends T> alternative, java.util.function.Consumer<? super java.lang.Throwable> exceptionConsumer)TorElseRecover(java.util.function.Function<? super java.lang.Throwable,? extends T> exceptionMapper)Gets the value contained in Try on success, otherwise maps the exception into a valid return value<X extends java.lang.Throwable>
TorElseSneakyThrow()Gets the Try value on success, otherwise sneaky throws the exception that caused the failure<X extends java.lang.Throwable>
TorElseThrow(java.util.function.Function<java.lang.Throwable,X> throwableSupplier)Gets the Try value on success, otherwise throws an exception generated by the provided throwable mapperTry<T>orElseTry(Try.TryMapper<java.lang.Throwable,Try<? extends T>> excToAlternative)Gets the current Try or if it is a failure maps the generated exception into an alternative Try using the specified mapperTry<T>orElseTry(Try.TryValueSupplier<? extends T> supplier)Gets the current Try or if it is a failure, the result of the provided TrySupplierTry<T>orElseTry(Try.TryValueSupplier<? extends T> supplier, UnChecked.CheckedConsumer<? super java.lang.Throwable> exceptionConsumer)Gets the current Try or if it is a failure, the result of the provided TrySupplier and the specified consumer process the exception that has generated the failureTry<T>orElseTry(Try<? extends T> alternative)Gets the value contained in Try on success, otherwise returns the specified Try<ExceptionT extends java.lang.Throwable>
Try<T>peek(java.lang.Class<? extends ExceptionT> throwableClass, java.util.function.Consumer<? super T> ifSuccess, java.util.function.Consumer<? super ExceptionT> ifError)Check the status of the current Try and apply accordingly one of the provided consumers.Try<T>peek(java.util.function.Consumer<? super T> ifSuccess, java.util.function.Consumer<? super java.lang.Throwable> ifError)Check the status of the current Try and apply accordingly one of the provided consumers.<ExceptionT extends java.lang.Throwable>
Try<T>peekFailure(java.lang.Class<ExceptionT> throwableClass, java.util.function.Consumer<ExceptionT> ifError)Check if the status of the current Try is a failure of the specified class and in that case apply the specified consumer to its failure cause.Try<T>peekFailure(java.util.function.Consumer<? super java.lang.Throwable> ifError)Check if the current Try is a Failure and in that case apply the specified consumer to its failure cause.Try<T>peekSuccess(java.util.function.Consumer<? super T> ifSuccess)Check the status of the current Try and if it is a success apply the specified consumer to its value.<X extends java.lang.Throwable>
Try<T>recover(java.lang.Class<X> exception, Try.TryMapper<? super java.lang.Throwable,? extends T> alternativeMapper)Recover the status of a Try, if failed, mapping the generated exception to another org .reacted.patterns.Try Will be returned the original Try if it is successful, otherwise the try returned by the mapper Different recover calls can be chains for fine exception handling<X extends java.lang.Throwable>
Try<T>recover(java.lang.Class<X> exception, Try.TryValueSupplier<? extends T> successValGenerator)Recover the status of a Try, if failed.<X extends java.lang.Throwable>
Try<T>recover(java.lang.Class<X> exception, Try<? extends T> successValue)Recover the status of a Try, if failed.<X extends java.lang.Throwable>
Try<T>recover(java.lang.Class<X> exception, UnChecked.CheckedSupplier<Try<? extends T>> successProvider)Recover the status of a Try, if failed, a success Try is generated using the provided supplier Will be returned the original Try if it is successful, otherwise the try returned by the mapper Different recover calls can be chains for fine exception handlingjava.util.stream.Stream<T>stream()Converts the Try into a java Stream.java.util.Optional<T>toOptional()static <T, A extends java.lang.AutoCloseable, A1 extends java.lang.AutoCloseable>
Try<T>withChainedResources(Try.TryResourceSupplier<? extends A> resourceSupplier1, Try.TryMapper<A,? extends A1> resourceMapper, UnChecked.CheckedBiFunction<? super A,? super A1,? extends T> resourceToResult)static <T, A extends java.lang.AutoCloseable>
Try<T>withResources(Try.TryResourceSupplier<? extends A> resourceSupplier, Try.TryMapper<? super A,? extends T> resourceToResult)Applies a consumer on a resource.static <T, A extends java.lang.AutoCloseable, A1 extends java.lang.AutoCloseable>
Try<T>withResources(Try.TryResourceSupplier<? extends A> resourceSupplier1, Try.TryResourceSupplier<? extends A1> resourceSupplier2, UnChecked.CheckedBiFunction<? super A,? super A1,? extends T> resourceToResult)Applies a consumer on two resources.
-
Field Details
-
Method Details
-
noOp
public static java.lang.Void noOp(java.lang.Object... args)Placeholder for a no operation- Parameters:
args- any number or type of args- Returns:
- Void
-
identity
Identity Try function. May be used as placeholder as mapper- Type Parameters:
U- any type- Parameters:
value- a Try- Returns:
- the same try passed as argument
-
identity
public static <U> U identity(U value)Identity function. May be used as placeholder as mapper- Type Parameters:
U- any type- Parameters:
value- any value- Returns:
- U the same value passed as input
-
isSuccess
public abstract boolean isSuccess()- Returns:
- true if the operation has been successful. False otherwise
-
isFailure
public boolean isFailure()- Returns:
- true if the operation has failed, true otherwise
-
getCause
public abstract java.lang.Throwable getCause()- Returns:
- Return the cause of a failure
-
get
This get will return the success value of a successful Try. Be aware that if the success value is a NULL, a Try.Success object will be returned whose value returned by get() is NULL Nulls can safely be used as return values with Try, just remember that you will get what you supply- Returns:
- get the success value for this Try.
-
toOptional
- Returns:
- An optional containing a non null value on Try success, empty otherwise
-
stream
Converts the Try into a java Stream. If the Try is successful and contains a non-null value, a stream containing that values is returned, otherwise an empty stream.anyCollection.stream() .flatMap(element -> Try.of(() -> riskyCall(element)).stream()) .collect(...)- Returns:
- A stream containing the Try a non-null value on success, empty otherwise
-
withResources
public static <T, A extends java.lang.AutoCloseable> Try<T> withResources(Try.TryResourceSupplier<? extends A> resourceSupplier, Try.TryMapper<? super A,? extends T> resourceToResult)Applies a consumer on a resource. The resource is automatically closed regardless of the result of the computationint stringLengthSum = Try.withResources(() -> Files.lines(path), inputStream -> inputStream.mapToInt(String::length) .sum()) .orElse(-1, Throwable::printStackTrace);- Type Parameters:
T- Mapper return typeA- Type of the AutoCloseable resource- Parameters:
resourceToResult- Mapper function that takes as input the resource and returns a valueresourceSupplier- Supplier for the AutoCloseable resource- Returns:
- try of the mapper result
-
withResources
public static <T, A extends java.lang.AutoCloseable, A1 extends java.lang.AutoCloseable> Try<T> withResources(Try.TryResourceSupplier<? extends A> resourceSupplier1, Try.TryResourceSupplier<? extends A1> resourceSupplier2, UnChecked.CheckedBiFunction<? super A,? super A1,? extends T> resourceToResult)Applies a consumer on two resources. The resources are automatically closed regardless of the result of the computationint stringLengthSum = Try.withResources(() -> Files.lines(path), () -> Files.lines(anotherPath), (firstInputStream, secondInputStream) -> Stream.concat(firstInputStream, secondInputStream) .mapToInt(String::length).sum()) .orElse(-1, Throwable::printStackTrace);- Type Parameters:
T- Return type of the mapperA- Type of the first AutoCloseable resourceA1- Type of the second AutoCloseable resource- Parameters:
resourceToResult- Mapper function that takes as input two resources and returns a valueresourceSupplier1- Supplier for the first resource argumentresourceSupplier2- Supplier for the second resource argument- Returns:
- a try of the mapper result
-
withChainedResources
public static <T, A extends java.lang.AutoCloseable, A1 extends java.lang.AutoCloseable> Try<T> withChainedResources(Try.TryResourceSupplier<? extends A> resourceSupplier1, Try.TryMapper<A,? extends A1> resourceMapper, UnChecked.CheckedBiFunction<? super A,? super A1,? extends T> resourceToResult) -
of
Creates a Try monad with the result of a computationTry.of(() -> anyCheckedOrUncheckedMethodYouWant(anyInput))- Type Parameters:
T- type contained in the Try- Parameters:
supplier- Supplier of the value contained in the Try- Returns:
- a Try containing the value generated by the supplier or failure
-
ofCallable
- Type Parameters:
T- Type returned by the callable- Parameters:
function- Callable used as supplier for the value of the Try- Returns:
- a Try containing the value generated by the callable or failure
-
ofRunnable
- Parameters:
function- a simple Runnable function- Returns:
- an anonymous Try containing, failed if it's the case, the exception thrown by the Runnable
-
ofSuccess
Creates a successful Try carrying the specified valued- Type Parameters:
T- type of the value- Parameters:
value- Value that is contained into the Try- Returns:
- a successful Try
-
ofFailure
Creates a failed Try carrying the specified failure exception- Type Parameters:
T- type of the failed Try- Parameters:
throwable- failure value for the Try- Returns:
- a failed Try containing the specified throwable as cause
-
orElseThrow
public <X extends java.lang.Throwable> T orElseThrow(java.util.function.Function<java.lang.Throwable,X> throwableSupplier) throws X extends java.lang.ThrowableGets the Try value on success, otherwise throws an exception generated by the provided throwable mappervar result = Try.of(() -> performComputation())).orElseThrow(ErrorOccurredException::new);- Type Parameters:
X- type of the thrown exception- Parameters:
throwableSupplier- Supplier of the exception that is going to be thrown if the Try is a failure- Returns:
- the value contained in the Try if it is successful
- Throws:
X- any exception
-
orElseSneakyThrow
Gets the Try value on success, otherwise sneaky throws the exception that caused the failurevar result = Try.of(() -> performComputation())).orElseSneakyThrow();- Type Parameters:
X- anyThrowable- Returns:
- the value contained in the Try if it is successful
- Throws:
X- Any Throwable of any type that might have been generated during the processing of the previous steps
-
orElse
Gets the value contained in Try on success, otherwise returns the specified value.var result = Try.of(() -> dangerousComputation()).orElse(anotherObject);- Type Parameters:
U- (sub)type of the alternative value- Parameters:
alternative- An alternative value to return in case the Try is a failure- Returns:
- the original value contained into the Try or the alternative one
-
orElseGet
Gets the value contained in Try on success, otherwise returns the output of the provided supplier.var result = Try.of(() -> dangerousComputation()).orElse(() -> generateAnotherObject());- Parameters:
alternative- supplier for generating an alternative value in case the Try is a failure- Returns:
- the original value contained into the Try or the one generated by the supplier
-
orElseGet
-
orElseGet
-
orElse
public T orElse(T alternative, java.util.function.Consumer<? super java.lang.Throwable> exceptionConsumer)Gets the value contained in Try on success, otherwise returns the specified value and the exception that generated the failure is processed with the provided consumervar result = Try.of(() -> dangerousComputation()).orElse(anotherObject, LOGGER::print);- Parameters:
alternative- an alternative Try that should be returned in case the main one is a failureexceptionConsumer- on failure, apply this consumer to the generated Throwable before returning the alternative value- Returns:
- the original Try or the alternative one
-
orElseRecover
public T orElseRecover(java.util.function.Function<? super java.lang.Throwable,? extends T> exceptionMapper)Gets the value contained in Try on success, otherwise maps the exception into a valid return valuevar result = Try.of(() -> dangerousComputation()).orElseRecover(exception -> exception.toString());- Parameters:
exceptionMapper- a function that should not throw any exception that maps the throwable to a valid T value- Returns:
- the original Try or the mapped one
-
orElseTry
Gets the value contained in Try on success, otherwise returns the specified Tryvar result = Try.of(() -> dangerousComputation()).orElse(anotherTryMonad);- Parameters:
alternative- an alternative Try that should be returned in case the main one is a failure- Returns:
- the original Try or the alternative one
-
orElseTry
Gets the current Try or if it is a failure, the result of the provided TrySuppliervar result = Try.of(() -> dangerousCall()).orElseTry(() -> anotherDangerousCall())- Parameters:
supplier- supplier for an alternative value in case the main Try is a failure- Returns:
- the original Try or the alternative one
-
orElseTry
public Try<T> orElseTry(Try.TryValueSupplier<? extends T> supplier, UnChecked.CheckedConsumer<? super java.lang.Throwable> exceptionConsumer)Gets the current Try or if it is a failure, the result of the provided TrySupplier and the specified consumer process the exception that has generated the failurevar result = Try.of(() -> dangerousCall()).orElseTry(() -> otherDangerousCall(), LOGGER::printFirstCallExc)- Parameters:
supplier- supplier for an alternative value in case the main Try is a failureexceptionConsumer- on failure, apply this consumer to the generated Throwable before calling the alternative value supplier- Returns:
- the original Try or the alternative one
-
orElseTry
Gets the current Try or if it is a failure maps the generated exception into an alternative Try using the specified mappervar result = Try.of(() -> dangerousCall()).orElseTry(throwable -> throwableToAnotherTry(throwable))- Parameters:
excToAlternative- if the main Try is a failure, the generated exception is taken as argument by this mapper for providing an alternate Try- Returns:
- the original value or the generated one if failure
-
flatMap
Like Stream.flatMap(), Try.flatMap flattens two nested Try. If the Try is successful the flatMapping function will be applied, otherwise the current Try will be returnedTry<String> result = Try.of(() -> dangerousCall()) .flatMap(dangerousResult -> Try.of(() -> anotherDangerousCall(dangerousResult))) .filter(secondCallResult -> !secondCallResult().isEmpty());- Type Parameters:
U- type of the argument of the returned Try- Parameters:
flatMapper- mapper that transforms the value of a successful Try into another Try- Returns:
- a failure or the flatmapped Try
-
map
If the Try is successful, another Try will be returned with the result of the specified mapper, otherwise the current Try is returnedTry<String> failedMap = Try.of(TryTests::failingCheckedThrower).map(String::toLowerCase); String result = failedMap.orElse(FAILURE);- Type Parameters:
U- type contained into the returned Try- Parameters:
mapper- mapper function for transforming a Try to another- Returns:
- the new Try on success or failure
-
filter
If the Try is a failure, the current Try is returned. If the try Is a success, its value is tested with the specified predicate. If such test is successful, the current Try is returned, otherwise a Failure is returnedString resultString = Try.of(() -> dangerousCallThatReturnsAString()) .filter(String::isUpperCase) .orElse("DEFAULT_UPPERCASE_VALUE");- Parameters:
predicate- filter predicate for filtering a successful Try. Is a success try does not pass the filter, a failed Try will be returned- Returns:
- a Try for which the predicate is true or failure
-
filter
public Try<T> filter(UnChecked.CheckedPredicate<? super T> predicate, java.util.function.Supplier<? extends java.lang.Throwable> exceptionOnTestFailure)If the Try is a failure, the current Try is returned. If the try Is a success, its value is tested with the specified predicate. If such test is successful, the current Try is returned, otherwise a Failure is returnedString resultString = Try.of(() -> dangerousCallThatReturnsAString()) .filter(String::isUpperCase) .orElse("DEFAULT_UPPERCASE_VALUE");- Parameters:
predicate- filter predicate for filtering a successful Try. Is a succeeded try does not pass the filter, a failed Try will be returnedexceptionOnTestFailure- if the predicate evaluates to false, the failure cause will be provided by this- Returns:
- a Try for which the predicate is true or failure
-
ifSuccess
If the Try is a success, the provided consumer is applied to the result. A io.reacted .patterns.Try is returned for checking the success or the failure of the consumerTry<Void> consumerResult = Try.ofSuccess(SUCCESS).ifSuccess(LOGGER::printSuccess);- Parameters:
consumer- Consumer for the value of a successful Try- Returns:
- an anonymous Try for checking if the consumer execution was successful
-
ifError
If Try is a failure, the provided consumer will be applied to the generated Throwable. A Try is returned for checking the success or the failure of the consumerTry<Void> consumerResult = Try.ofFailure(AnyThrowable).ifError(LOGGER::printError);- Parameters:
consumer- Consumer for the exception contained in a failed Try- Returns:
- an anonymous Try for checking if the consumer execution was successful
-
recover
public <X extends java.lang.Throwable> Try<T> recover(java.lang.Class<X> exception, Try.TryValueSupplier<? extends T> successValGenerator)Recover the status of a Try, if failed. If the Try is failed because of an exception of the specified class, a new Try will be returned using the provided supplier. If the exception class does not match, the original failed Try is returned. Different recover calls can be chains for fine exception handlingTry<String> catchSpecificException = Try.of(() -> riskyCallReturningString()) .recover(StringIndexOutOfBoundException.class, () -> Try.ofSuccess("Whooops"))- Type Parameters:
X- Exception type we want to intercept- Parameters:
exception- Exception class we want to interceptsuccessValGenerator- Supplier for an alternate Try in case the provided exception class is intercepted- Returns:
- a successful Try, the generated one in case the provided exception class is intercepted or failure
-
recover
public <X extends java.lang.Throwable> Try<T> recover(java.lang.Class<X> exception, Try<? extends T> successValue)Recover the status of a Try, if failed. If the Try is failed because of an exception of the specified class, the provided Try will be returned. If the exception class does not match, the original failed Try is returned Different recover calls can be chains for fine exception handlingTry<String> catchSpecificException = Try.of(() -> dangerousCallReturningString()) .recover(StringIndexOutOfBoundException.class, Try.ofSuccess("Whooops"))- Type Parameters:
X- Exception type we want to intercept- Parameters:
exception- Exception class we want to interceptsuccessValue- alternate Try to be returned in case the provided exception class is intercepted- Returns:
- a successful Try, the generated one in case the provided exception class is intercepted or failure
-
recover
public <X extends java.lang.Throwable> Try<T> recover(java.lang.Class<X> exception, UnChecked.CheckedSupplier<Try<? extends T>> successProvider)Recover the status of a Try, if failed, a success Try is generated using the provided supplier Will be returned the original Try if it is successful, otherwise the try returned by the mapper Different recover calls can be chains for fine exception handlingTry<String> catchSpecificException = Try.of(() -> dangerousCallReturningString()) .recover(StringIndexOutOfBoundException.class, () -> Try.ofSuccess("Whooops"))- Type Parameters:
X- Exception type we want to intercept- Parameters:
exception- Exception class we want to interceptsuccessProvider- Supplier for the successful try- Returns:
- a Try representing the result of the alternative mapping process or the original Try
-
recover
public <X extends java.lang.Throwable> Try<T> recover(java.lang.Class<X> exception, Try.TryMapper<? super java.lang.Throwable,? extends T> alternativeMapper)Recover the status of a Try, if failed, mapping the generated exception to another org .reacted.patterns.Try Will be returned the original Try if it is successful, otherwise the try returned by the mapper Different recover calls can be chains for fine exception handlingTry<String> catchSpecificException = Try.of(() -> dangerousCallReturningString()) .recover(StringIndexOutOfBoundException.class, exception -> Try.ofSuccess("Whooops: " + exception))- Type Parameters:
X- Exception type we want to intercept- Parameters:
exception- Exception class we want to interceptalternativeMapper- Mapper that transforms an exception value to a valid result- Returns:
- a Try representing the result of the alternative mapping process or the original Try
-
peekSuccess
Check the status of the current Try and if it is a success apply the specified consumer to its value. The Try is left untouched and is returnedTry.of(() -> anyCheckedOrUncheckedMethodYouWant(line)) .peekSuccess(LOGGER::printDebugDiagnostics)- Parameters:
ifSuccess- consumer for the Try value in case the Try is a success- Returns:
- the untouched Try
-
peekFailure
Check if the current Try is a Failure and in that case apply the specified consumer to its failure cause. The Try is left untouched and is returnedTry.of(() -> anyCheckedOrUncheckedMethodYouWant(line)) .peekFailure(LOGGER::printDebugDiagnostics)- Parameters:
ifError- if Try is a failure, consumer will be applied to the contained exception- Returns:
- the untouched Try
-
peekFailure
public <ExceptionT extends java.lang.Throwable> Try<T> peekFailure(java.lang.Class<ExceptionT> throwableClass, java.util.function.Consumer<ExceptionT> ifError)Check if the status of the current Try is a failure of the specified class and in that case apply the specified consumer to its failure cause. The Try is left untouched and is returnedTry.of(() -> methodThrowingAnException(line)) .peekFailure(ExceptionClassYouWantToIntercept.class, LOGGER::printDebugDiagnostics)- Type Parameters:
ExceptionT- The type of error that should be peeked- Parameters:
ifError- if Try is a failure, consumer will be applied to the contained exceptionthrowableClass- inspect if the failure belongs to the specified class- Returns:
- the untouched Try
-
peek
public Try<T> peek(java.util.function.Consumer<? super T> ifSuccess, java.util.function.Consumer<? super java.lang.Throwable> ifError)Check the status of the current Try and apply accordingly one of the provided consumers. The Try is left untouched and is returnedTry.of(() -> anyCheckedOrUncheckedMethodYouWant(line)) .peek(LOGGER::print, LOGGER::debug)- Parameters:
ifSuccess- consumer for the Try value in case the Try is a successifError- consumer for the Throwable in case Try is a failure- Returns:
- the untouched Try
-
peek
public <ExceptionT extends java.lang.Throwable> Try<T> peek(java.lang.Class<? extends ExceptionT> throwableClass, java.util.function.Consumer<? super T> ifSuccess, java.util.function.Consumer<? super ExceptionT> ifError)Check the status of the current Try and apply accordingly one of the provided consumers. The ifError consumer is applied only if this Try is an error and the cause is of the specified class. The Try is left untouched and is returnedTry.of(() -> anyCheckedOrUncheckedMethodYouWant(line)) .peek(SpecificException.class, LOGGER::print, LOGGER::debug)- Type Parameters:
ExceptionT- Any exception or error type that we want to peek- Parameters:
throwableClass- specific throwable class we want to intercept for applying ifErrorifSuccess- consumer for the Try value in case the Try is a successifError- consumer for the Throwable in case Try is a failure- Returns:
- the untouched Try
-
mapOrElse
public <U> Try<U> mapOrElse(Try.TryMapper<? super T,? extends U> ifSuccess, Try.TryMapper<? super java.lang.Throwable,? extends U> orElse)A functional if then else: if the Try is successful the ifSuccess mapper is used, otherwise the throwable mapper.Try.of(() -> riskyCall()) .mapOrElse(processOutput, exception -> Try.of(() -> tryToRecover()).orElse(PERMANENT_FAILURE)) .orElse(DEFAULT_RESULT)- Type Parameters:
U- the type of the value of the resulting Try- Parameters:
ifSuccess- mapper in case the Try is a successorElse- mapper in case the Try is a failure- Returns:
- a Try mapped accordingly with the status of the base object
-
ifSuccessOrElse
public Try<java.lang.Void> ifSuccessOrElse(Try.TryConsumer<? super T> successConsumer, Try.TryConsumer<? super java.lang.Throwable> failureConsumer)A functional if then else: if the Try is successful the successConsumer is used, otherwise the throwable consumer.Try.of(() -> riskyCall()) .ifSuccessOrElse(processOutput, LOGGER::warn)- Parameters:
successConsumer- consumer in case the Try is a successfailureConsumer- consumer in case the Try is a failure- Returns:
- a Try representing the result of the applied consumer
-