Skip to content

tfij/result

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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>

About

Functional way to handle errors in java

Resources

Stars

Watchers

Forks

Packages

No packages published