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 class  Try.Failure<T>  
    static class  Try.Success<T>  
    static interface  Try.TryConsumer<T>  
    static interface  Try.TryMapper<T,​R>  
    static interface  Try.TryResourceSupplier<T>  
    static interface  Try.TryValueSupplier<T>  
  • Field Summary

    Fields 
    Modifier and Type Field Description
    static Try<java.lang.Void> VOID  
  • 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 T get()
    This get will return the success value of a successful Try.
    abstract java.lang.Throwable getCause()  
    static <U> Try<U> identity​(Try<U> value)
    Identity Try function.
    static <U> U identity​(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.
    boolean isFailure()  
    abstract boolean isSuccess()  
    <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.Void noOp​(java.lang.Object... args)
    Placeholder for a no operation
    static <T> Try<T> of​(Try.TryValueSupplier<? extends T> supplier)
    Creates a Try monad with the result of a computation
    static <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 exception
    static Try<java.lang.Void> ofRunnable​(UnChecked.CheckedRunnable function)  
    static <T> Try.Success<T> ofSuccess​(T value)
    Creates a successful Try carrying the specified valued
    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 consumer
    <U extends T>
    T
    orElse​(U alternative)
    Gets the value contained in Try on success, otherwise returns the specified value.
    T orElseGet​(java.util.function.Function<? super java.lang.Throwable,​? extends T> exceptionMapper)  
    T orElseGet​(java.util.function.Supplier<? extends T> alternative)
    Gets the value contained in Try on success, otherwise returns the output of the provided supplier.
    T orElseGet​(java.util.function.Supplier<? extends T> alternative, java.util.function.Consumer<? super java.lang.Throwable> exceptionConsumer)  
    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 value
    <X extends java.lang.Throwable>
    T
    orElseSneakyThrow()
    Gets the Try value on success, otherwise sneaky throws the exception that caused the failure
    <X extends java.lang.Throwable>
    T
    orElseThrow​(java.util.function.Function<java.lang.Throwable,​X> throwableSupplier)
    Gets the Try value on success, otherwise throws an exception generated by the provided throwable mapper
    Try<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 mapper
    Try<T> orElseTry​(Try.TryValueSupplier<? extends T> supplier)
    Gets the current Try or if it is a failure, the result of the provided TrySupplier
    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 failure
    Try<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 handling
    java.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.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • VOID

      public static final Try<java.lang.Void> VOID
  • 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

      public static <U> Try<U> identity​(Try<U> value)
      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

      public abstract T 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

      public java.util.Optional<T> toOptional()
      Returns:
      An optional containing a non null value on Try success, empty otherwise
    • stream

      public java.util.stream.Stream<T> 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 computation
      
       int stringLengthSum = Try.withResources(() -> Files.lines(path),
                                               inputStream -> inputStream.mapToInt(String::length)
                                                                         .sum())
                                .orElse(-1, Throwable::printStackTrace);
       
      Type Parameters:
      T - Mapper return type
      A - Type of the AutoCloseable resource
      Parameters:
      resourceToResult - Mapper function that takes as input the resource and returns a value
      resourceSupplier - 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 computation
      
       int 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 mapper
      A - Type of the first AutoCloseable resource
      A1 - Type of the second AutoCloseable resource
      Parameters:
      resourceToResult - Mapper function that takes as input two resources and returns a value
      resourceSupplier1 - Supplier for the first resource argument
      resourceSupplier2 - 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

      public static <T> Try<T> of​(Try.TryValueSupplier<? extends T> supplier)
      Creates a Try monad with the result of a computation
      Try.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

      public static <T> Try<T> ofCallable​(UnChecked.CheckedCallable<? extends T> function)
      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

      public static Try<java.lang.Void> ofRunnable​(UnChecked.CheckedRunnable function)
      Parameters:
      function - a simple Runnable function
      Returns:
      an anonymous Try containing, failed if it's the case, the exception thrown by the Runnable
    • ofSuccess

      public static <T> Try.Success<T> ofSuccess​(T value)
      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

      public static <T> Try.Failure<T> ofFailure​(java.lang.Throwable throwable)
      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.Throwable
      Gets the Try value on success, otherwise throws an exception generated by the provided throwable mapper
      
       var 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

      public <X extends java.lang.Throwable> T orElseSneakyThrow() throws X extends java.lang.Throwable
      Gets the Try value on success, otherwise sneaky throws the exception that caused the failure
      
       var result = Try.of(() -> performComputation())).orElseSneakyThrow();
       
      Type Parameters:
      X - any Throwable
      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

      public <U extends T> T orElse​(U alternative)
      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

      public T orElseGet​(java.util.function.Supplier<? extends T> alternative)
      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

      public T orElseGet​(java.util.function.Supplier<? extends T> alternative, java.util.function.Consumer<? super java.lang.Throwable> exceptionConsumer)
    • orElseGet

      public T orElseGet​(java.util.function.Function<? super java.lang.Throwable,​? extends T> exceptionMapper)
    • 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 consumer
      
        var result = Try.of(() -> dangerousComputation()).orElse(anotherObject, LOGGER::print);
        
      Parameters:
      alternative - an alternative Try that should be returned in case the main one is a failure
      exceptionConsumer - 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 value
      
       var 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

      public Try<T> orElseTry​(Try<? extends T> alternative)
      Gets the value contained in Try on success, otherwise returns the specified Try
      
       var 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

      public Try<T> orElseTry​(Try.TryValueSupplier<? extends T> supplier)
      Gets the current Try or if it is a failure, the result of the provided TrySupplier
      
       var 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 failure
      
       var result = Try.of(() -> dangerousCall()).orElseTry(() -> otherDangerousCall(), LOGGER::printFirstCallExc)
       
      Parameters:
      supplier - supplier for an alternative value in case the main Try is a failure
      exceptionConsumer - on failure, apply this consumer to the generated Throwable before calling the alternative value supplier
      Returns:
      the original Try or the alternative one
    • orElseTry

      public Try<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 mapper
      
       var 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

      public <U> Try<U> flatMap​(Try.TryMapper<? super T,​Try<? extends U>> flatMapper)
      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 returned
      
       Try<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

      public <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
      
       Try<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

      public Try<T> filter​(UnChecked.CheckedPredicate<? super T> predicate)
      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 returned
      
       String 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 returned
      
       String 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 returned
      exceptionOnTestFailure - 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

      public Try<java.lang.Void> ifSuccess​(Try.TryConsumer<? super T> consumer)
      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 consumer
      
       Try<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

      public 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. A Try is returned for checking the success or the failure of the consumer
      
       Try<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 handling
      
       Try<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 intercept
      successValGenerator - 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 handling
      
       Try<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 intercept
      successValue - 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 handling
      
       Try<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 intercept
      successProvider - 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 handling
      
       Try<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 intercept
      alternativeMapper - 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

      public 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. The Try is left untouched and is returned
      
       Try.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

      public 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. The Try is left untouched and is returned
      
       Try.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 returned
      
       Try.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 exception
      throwableClass - 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 returned
      
       Try.of(() -> anyCheckedOrUncheckedMethodYouWant(line))
          .peek(LOGGER::print, LOGGER::debug)
       
      Parameters:
      ifSuccess - consumer for the Try value in case the Try is a success
      ifError - 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 returned
      
       Try.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 ifError
      ifSuccess - consumer for the Try value in case the Try is a success
      ifError - 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 success
      orElse - 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 success
      failureConsumer - consumer in case the Try is a failure
      Returns:
      a Try representing the result of the applied consumer