Functional way to handle errors in java
Groovy Java
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
gradle/wrapper
src
.gitignore
.travis.yml
README.md
build.gradle
gradlew
gradlew.bat
settings.gradle

README.md

result - Functional way to handle errors in java

Travis Sonatype Nexus (Releases)

The inspiration for this project was the functional approach to error handling, such as in scala. The scala has types Either and Try.

The first one is more generic, it lets to use any type of error class. On the other hand, to handle an error, checking an instance of subclass (in scala with a pattern matting) or calling a method like isLeft() is required.

Try is a monad with fluent API, unfortunately there's no possibility to use a custom error class.

I prepare Result type which solves both problems. This type allow to have a custom error type and use fluent API with methods like map(), flatMap(), getOrElse() and so on.

Code example

double discount = 0.2;
double DEFAULT_PRICE = 100;
String priceInput = ""; // not validated input
double calcylatedPrice = Result.tryToDo(() -> Double.parseDouble(priceInput))
        .map(price -> price * discount)
        .peekError(error -> log.warn(error.getMessage()))
        .getOrElse(DEFAULT_PRICE);

Maven

<dependency>
  <groupId>pl.tfij</groupId>
  <artifactId>result</artifactId>
  <version>1.0</version>
</dependency>