Faux Pas

Error handling in Functional Programming

License

License

Categories

Categories

Faux Pas Development Tools Development Libraries
GroupId

GroupId

org.zalando
ArtifactId

ArtifactId

faux-pas
Last Version

Last Version

0.9.0
Release Date

Release Date

Type

Type

jar
Description

Description

Faux Pas
Error handling in Functional Programming
Project URL

Project URL

https://github.com/zalando/faux-pas
Project Organization

Project Organization

Zalando SE
Source Code Management

Source Code Management

https://github.com/zalando/faux-pas

Download faux-pas

How to add to project

<!-- https://jarcasting.com/artifacts/org.zalando/faux-pas/ -->
<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>faux-pas</artifactId>
    <version>0.9.0</version>
</dependency>
// https://jarcasting.com/artifacts/org.zalando/faux-pas/
implementation 'org.zalando:faux-pas:0.9.0'
// https://jarcasting.com/artifacts/org.zalando/faux-pas/
implementation ("org.zalando:faux-pas:0.9.0")
'org.zalando:faux-pas:jar:0.9.0'
<dependency org="org.zalando" name="faux-pas" rev="0.9.0">
  <artifact name="faux-pas" type="jar" />
</dependency>
@Grapes(
@Grab(group='org.zalando', module='faux-pas', version='0.9.0')
)
libraryDependencies += "org.zalando" % "faux-pas" % "0.9.0"
[org.zalando/faux-pas "0.9.0"]

Dependencies

compile (3)

Group / Artifact Type Version
org.apiguardian : apiguardian-api jar 1.1.1
com.google.code.findbugs : jsr305 jar 3.0.2
org.slf4j : slf4j-api jar 1.7.30

provided (2)

Group / Artifact Type Version
com.google.gag : gag jar 1.0.1
org.projectlombok : lombok jar 1.18.16

test (5)

Group / Artifact Type Version
org.slf4j : slf4j-nop jar 1.7.30
org.junit.jupiter : junit-jupiter-engine jar 5.7.0
org.assertj : assertj-core jar 3.18.1
org.mockito : mockito-core jar 3.6.28
org.mockito : mockito-junit-jupiter jar 3.6.28

Project Modules

There are no modules declared in this project.

Faux Pas: Error handling in Functional Programming

Spilled coffee

Stability: Sustained Build Status Coverage Status Code Quality Javadoc Release Maven Central License

Faux pas noun, /fəʊ pɑː/: blunder; misstep, false step

Faux Pas is a library that simplifies error handling for Functional Programming in Java. It fixes the issue that none of the functional interfaces in the Java Runtime by default is allowed to throw checked exceptions.

  • Technology stack: Java 8+, functional interfaces
  • Status: 0.x, originally ported from Riptide, used in production

Example

interface Client {
    User read(final String name) throws IOException;
}

Function<String, User> readUser = throwingFunction(client::read);
readUser.apply("Bob"); // may throw IOException directly

Features

  • Checked exceptions for functional interfaces
  • Compatible with the JDK types

Dependencies

  • Java 8 or higher
  • Lombok (no runtime dependency)

Installation

Add the following dependency to your project:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>faux-pas</artifactId>
    <version>${faux-pas.version}</version>
</dependency>

Usage

Throwing functional interfaces

Faux Pas has a variant of every major functional interface from the Java core:

The followings statements apply to each of them:

  • extends the official interface, i.e. they are 100% compatible
  • sneakily throws the original exception

Creation

The way the Java runtime implemented functional interfaces always requires additional type information, either by using a cast or a local variable:

// compiler error
client::read.apply(name);

// too verbose
((ThrowingFunction<String, User, IOException>) client::read).apply(name);

// local variable may not always be desired
ThrowingFunction<String, User, IOException> readUser = client::read;
readUser.apply(name);

As a workaround there is a static factory method for every interface type inFauxPas. All of them are called throwingRunnable, throwingSupplier and so forth. It allows for concise one-line statements:

List<User> users = names.stream()
    .map(throwingFunction(client::read))
    .collect(toList());

Try-with-resources alternative

Traditional try-with-resources statements are compiled into byte code that includes unreachable parts and unfortunately JaCoCo has no support for filtering yet. That's why we came up with an alternative implementation. The official example for the try-with-resources statement looks like this:

try (BufferedReader br =
               new BufferedReader(new FileReader(path))) {
    return br.readLine();
}

Compared to ours:

return tryWith(new BufferedReader(new FileReader(path)), br -> 
    br.readLine()
);

CompletableFuture.exceptionally(Function)

CompletableFuture.exceptionally(..) is a very powerful but often overlooked tool. It allows to inject partial exception handling into a CompletableFuture:

future.exceptionally(e -> {
    Throwable t = e instanceof CompletionException ? e.getCause() : e;

    if (t instanceof NoRouteToHostException) {
        return fallbackValueFor(e);
    }

    throw e instanceof CompletionException ? e : new CompletionException(t);
})

Unfortunately it has a contract that makes it harder to use than it needs to:

In order to use the operation correctly one needs to follow these rules:

  1. Unwrap given throwable if it's an instance of CompletionException.
  2. Wrap checked exceptions in a CompletionException before throwing.

FauxPas.partially(..) relives some of the pain by changing the interface and contract a bit to make it more usable. The following example is functionally equivalent to the one from above:

future.exceptionally(partially(e -> {
    if (e instanceof NoRouteToHostException) {
        return fallbackValueFor(e);
    }

    throw e;
}))
  1. Takes a ThrowingFunction<Throwable, T, Throwable>, i.e. it allows clients to
    • directly re-throw the throwable argument
    • throw any exception during exception handling as-is
  2. Will automatically unwrap a CompletionException before passing it to the given function. I.e. the supplied function will never have to deal with CompletionException directly. Except for the rare occasion that the CompletionException has no cause, in which case it will be passed to the given function.
  3. Will automatically wrap any thrown Exception inside a CompletionException, if needed.

The last example is actually so common, that there is an overloaded version of partially that caters for this use particular case:

future.exceptionally(partially(NoRouteToHostException.class, this::fallbackValueFor))

CompletableFuture.whenComplete(BiConsumer)

future.whenComplete(failedWith(TimeoutException.class, e -> {
    request.cancel();
}))

Other missing pieces in CompletableFuture's API are exceptionallyCompose and handleCompose. Both can be seen as a combination of exceptionally + compose and handle + compose respectively. They basically allow to supply another CompletableFuture rather than concrete values directly. This is allows for asynchronous fallbacks:

exceptionallyCompose(users.find(name), e -> archive.find(name))

Getting Help

If you have questions, concerns, bug reports, etc., please file an issue in this repository's Issue Tracker.

Getting Involved/Contributing

To contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. For more details, check the contribution guidelines.

Alternatives

org.zalando

Zalando SE

The org page for Zalando, Europe's leading online fashion platform. Visit opensource.zalando.com for project stats.

Versions

Version
0.9.0
0.8.0
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.1
0.3.0
0.2.0
0.1.0