aol / cyclops-integration

Home of the cyclops integration modules : support for Scala, Clojure, RxJava (1+2), Reactor, FunctionalJava, Guava, Dexx & Vavr
http://cyclops-react.io
MIT License
442 stars 51 forks source link

How to re-throw exception? #284

Closed volisoft closed 7 years ago

volisoft commented 7 years ago

The documentation states that Try's monad behavior is inline with current Java development practices. However, I cannot figure out how to re-throw exception and/or wrap it into other exception type (e.g. based on some condition). Could you provide an example?

johnmcclean commented 7 years ago

Hey @volisoft you can do both via the visit method

Wrapping


     Try<String,IOException> result;

     Try<String,CustomException> wrapped = result.visit(Try::success,e->Try.failure(new CustomException(e)));

Conditional wrapping or throwing (with Exception softening / sneaky throws)

     Try<String,IOException> result;

      Try<String,CustomException> wrapped = result.visit(Try::success,e->{ return conditionHold(e) ? Try.failure(new CustomeException(e) : throw ExceptionSoftener.throwSoftenedException(e);});

The get() method will throw an Exception if the Try has failed (in much the same way as a CompletableFuture or Optional will) and there is also a throwException method, that will throw the Exception if present.

'visit' is an eager operation (it folds over the structure of the Try), if you need to change the exception type lazily (or reactively) you can use toXor() followed by secondaryMap and convert back to a new Try type.


just.toXor()
      .secondaryMap(x-> new CustomException(x))
      .toTry(CustomException.class);
volisoft commented 7 years ago

Awesome