• Stars
    star
    851
  • Rank 51,380 (Top 2 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Java library that implements application/problem+json

Problem

Bubble Gum on Shoe

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

Problem noun, /ˈpΙΉΙ’blΙ™m/: A difficulty that has to be resolved or dealt with.

Problem is a library that implements application/problem+json. It comes with an extensible set of interfaces/implementations as well as convenient functions for every day use. It's decoupled from any JSON library, but contains a separate module for Jackson.

Features

  • proposes a common approach for expressing errors in REST API implementations
  • compatible with application/problem+json

Dependencies

  • Java 8
  • Any build tool using Maven Central, or direct download
  • Jackson (optional)
  • Gson (optional)

Installation

Add the following dependency to your project:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>problem</artifactId>
    <version>${problem.version}</version>
</dependency>
<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>jackson-datatype-problem</artifactId>
    <version>${problem.version}</version>
</dependency>
<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>problem-gson</artifactId>
    <version>${problem.version}</version>
</dependency>

Java Modules

Even though the minimum requirement is still Java 8, all modules are Java 9 compatible:

module org.example {
    requires org.zalando.problem;
    // pick needed dependencies
    requires org.zalando.problem.jackson;
    requires org.zalando.problem.gson;
}

Configuration

In case you're using Jackson, make sure you register the module with your ObjectMapper:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new ProblemModule());

Alternatively, you can use the SPI capabilities:

ObjectMapper mapper = new ObjectMapper()
    .findAndRegisterModules();

Usage

Creating problems

There are different ways to express problems. Ranging from limited, but easy-to-use to highly flexible and extensible, yet with slightly more effort:

Generic

There are cases in which an HTTP status code is basically enough to convey the necessary information. Everything you need is the status you want to respond with and we will create a problem from it:

Problem.valueOf(Status.NOT_FOUND);

Will produce this:

{
  "title": "Not Found",
  "status": 404
}

As specified by Predefined Problem Types:

The "about:blank" URI, when used as a problem type, indicates that the problem has no additional semantics beyond that of the HTTP status code.

When "about:blank" is used, the title SHOULD be the same as the recommended HTTP status phrase for that code (e.g., "Not Found" for 404, and so on), although it MAY be localized to suit client preferences (expressed with the Accept-Language request header).

But you may also have the need to add some little hint, e.g. as a custom detail of the problem:

Problem.valueOf(Status.SERVICE_UNAVAILABLE, "Database not reachable");

Will produce this:

{
  "title": "Service Unavailable",
  "status": 503,
  "detail": "Database not reachable"
}

Builder

Most of the time you'll need to define specific problem types, that are unique to your application. And you want to construct problems in a more flexible way. This is where the Problem Builder comes into play. It offers a fluent API and allows to construct problem instances without the need to create custom classes:

Problem.builder()
    .withType(URI.create("https://example.org/out-of-stock"))
    .withTitle("Out of Stock")
    .withStatus(BAD_REQUEST)
    .withDetail("Item B00027Y5QG is no longer available")
    .build();

Will produce this:

{
  "type": "https://example.org/out-of-stock",
  "title": "Out of Stock",
  "status": 400,
  "detail": "Item B00027Y5QG is no longer available"
}

Alternatively you can add custom properties, i.e. others than type, title, status, detail and instance:

Problem.builder()
    .withType(URI.create("https://example.org/out-of-stock"))
    .withTitle("Out of Stock")
    .withStatus(BAD_REQUEST)
    .withDetail("Item B00027Y5QG is no longer available")
    .with("product", "B00027Y5QG")
    .build();

Will produce this:

{
  "type": "https://example.org/out-of-stock",
  "title": "Out of Stock",
  "status": 400,
  "detail": "Item B00027Y5QG is no longer available",
  "product": "B00027Y5QG"
}

Custom Problems

The highest degree of flexibility and customizability is achieved by implementing Problem directly. This is especially convenient if you refer to it in a lot of places, i.e. it makes it easier to share. Alternatively you can extend AbstractThrowableProblem:

@Immutable
public final class OutOfStockProblem extends AbstractThrowableProblem {

    static final URI TYPE = URI.create("https://example.org/out-of-stock");

    private final String product;

    public OutOfStockProblem(final String product) {
        super(TYPE, "Out of Stock", BAD_REQUEST, format("Item %s is no longer available", product));
        this.product = product;
    }

    public String getProduct() {
        return product;
    }

}
new OutOfStockProblem("B00027Y5QG");

Will produce this:

{
  "type": "https://example.org/out-of-stock",
  "title": "Out of Stock",
  "status": 400,
  "detail": "Item B00027Y5QG is no longer available",
  "product": "B00027Y5QG"
}

Throwing problems

Problems have a loose, yet direct connection to Exceptions. Most of the time you'll find yourself transforming one into the other. To make this a little bit easier there is an abstract Problem implementation that subclasses RuntimeException: the ThrowableProblem. It allows to throw problems and is already in use by all default implementations. Instead of implementing the Problem interface, just inherit from AbstractThrowableProblem:

public final class OutOfStockProblem extends AbstractThrowableProblem {
    // constructor
}

If you already have an exception class that you want to extend, you should implement the "marker" interface Exceptional:

public final class OutOfStockProblem extends BusinessException implements Exceptional

The Jackson support module will recognize this interface and deal with the inherited properties from Throwable accordingly. Note: This interface only exists, because Throwable is a concrete class, rather than an interface.

Handling problems

Reading problems is very specific to the JSON parser in use. This section assumes you're using Jackson, in which case reading/parsing problems usually boils down to this:

Problem problem = mapper.readValue(.., Problem.class);

If you're using Jackson, please make sure you understand its Polymorphic Deserialization feature. The supplied Jackson module makes heavy use of it. Considering you have a custom problem type OutOfStockProblem, you'll need to register it as a subtype:

mapper.registerSubtypes(OutOfStockProblem.class);

You also need to make sure you assign a @JsonTypeName to it and declare a @JsonCreator:

@JsonTypeName(OutOfStockProblem.TYPE_VALUE)
public final class OutOfStockProblem implements Problem {

    @JsonCreator
    public OutOfStockProblem(final String product) {

Jackson is now able to deserialize specific problems into their respective types. By default, e.g. if a type is not associated with a class, it will fallback to a DefaultProblem.

Catching problems

If you read about Throwing problems already, you should be familiar with ThrowableProblem. This can be helpful if you read a problem, as a response from a server, and what to find out what it actually is. Multiple if statements with instanceof checks could be an option, but usually nicer is this:

try {
    throw mapper.readValue(.., ThrowableProblem.class);
} catch (OutOfStockProblem e) {
    tellTheCustomerTheProductIsNoLongerAvailable(e.getProduct());
} catch (InsufficientFundsProblem e) {
    askCustomerToUseDifferentPaymentMethod(e.getBalance(), e.getDebit());
} catch (InvalidCouponProblem e) {
    askCustomerToUseDifferentCoupon(e.getCouponCode());
} catch (ThrowableProblem e) {
    tellTheCustomerSomethingWentWrong();
}

If you used the Exceptional interface rather than ThrowableProblem you have to adjust your code a little bit:

try {
    throw mapper.readValue(.., Exceptional.class).propagate();
} catch (OutOfStockProblem e) {
    ...

Stack traces and causal chains

Exceptions in Java can be chained/nested using causes. ThrowableProblem adapts the pattern seamlessly to problems:

ThrowableProblem problem = Problem.builder()
    .withType(URI.create("https://example.org/order-failed"))
    .withTitle("Order failed")
    .withStatus(BAD_REQUEST)
    .withCause(Problem.builder()
      .withType(URI.create("https://example.org/out-of-stock"))
      .withTitle("Out of Stock")
      .withStatus(BAD_REQUEST)
      .build())
    .build();
    
problem.getCause(); // standard API of java.lang.Throwable

Will produce this:

{
  "type": "https://example.org/order-failed",
  "title": "Order failed",
  "status": 400,
  "cause": {
    "type": "https://example.org/out-of-stock",
    "title": "Out of Stock",
    "status": 400,
    "detail": "Item B00027Y5QG is no longer available"
  }
}

Another important aspect of exceptions are stack traces, but since they leak implementation details to the outside world, we strongly advise against exposing them in problems. That being said, there is a legitimate use case when you're debugging an issue on an integration environment and you don't have direct access to the log files. Serialization of stack traces can be enabled on the problem module:

ObjectMapper mapper = new ObjectMapper()
    .registerModule(new ProblemModule().withStackTraces());

After enabling stack traces all problems will contain a stacktrace property:

{
  "type": "about:blank",
  "title": "Unprocessable Entity",
  "status": 400,
  "stacktrace": [
    "org.example.Example.execute(Example.java:17)",
    "org.example.Example.main(Example.java:11)"
  ]
}

Since we discourage the serialization of them, there is currently, by design, no way to deserialize them from JSON. Nevertheless the runtime will fill in the stack trace when the problem instance is created. That stack trace is usually not 100% correct, since it looks like the exception originated inside your deserialization framework. Problem comes with a special service provider interface StackTraceProcessor that can be registered using the ServiceLoader capabilities. It can be used to modify the stack trace, e.g. remove all lines before your own client code, e.g. Jackson/HTTP client/etc.

public interface StackTraceProcessor {

    Collection<StackTraceElement> process(final Collection<StackTraceElement> elements);

}

By default no processing takes place.

Getting help

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

Getting involved

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.

Credits and references

Spring Framework

Users of the Spring Framework are highly encouraged to check out Problems for Spring Web MVC, a library that seemlessly integrates problems into Spring.

Micronaut Framework

Users of the Micronaut Framework are highly encouraged to check out Micronaut Problem JSON , a library that seemlessly integrates problems into Micronaut error processing.

Quarkus Framework

Users of the Quarkus Framework are highly encouraged to check out Quarkus RESTeasy Problem Extension, a library that seemlessly integrates problems into Quarkus RESTeasy/JaxRS error processing. It also handles Problem-family exceptions from org.zalando:problem library.

More Repositories

1

patroni

A template for PostgreSQL High Availability with Etcd, Consul, ZooKeeper, or Kubernetes
Python
6,058
star
2

postgres-operator

Postgres operator creates and manages PostgreSQL clusters running in Kubernetes
Go
3,686
star
3

skipper

An HTTP router and reverse proxy for service composition, including use cases like Kubernetes Ingress
Go
3,005
star
4

zalenium

A flexible and scalable container based Selenium Grid with video recording, live preview, basic auth & dashboard.
Java
2,380
star
5

restful-api-guidelines

A model set of guidelines for RESTful APIs and Events, created by Zalando
CSS
2,067
star
6

SwiftMonkey

A framework for doing randomised UI testing of iOS apps
Swift
1,945
star
7

tailor

A streaming layout service for front-end microservices
JavaScript
1,726
star
8

logbook

An extensible Java library for HTTP request and response logging
Java
1,684
star
9

tech-radar

Visualizing our technology choices
1,491
star
10

spilo

Highly available elephant herd: HA PostgreSQL cluster using Docker
Python
1,225
star
11

intellij-swagger

A plugin to help you easily edit Swagger and OpenAPI specification files inside IntelliJ IDEA
Java
1,160
star
12

problem-spring-web

A library for handling Problems in Spring Web MVC
Java
997
star
13

nakadi

A distributed event bus that implements a RESTful API abstraction on top of Kafka-like queues
Java
928
star
14

zally

A minimalistic, simple-to-use API linter
Kotlin
873
star
15

zalando-howto-open-source

Open Source guidance from Zalando, Europe's largest online fashion platform
799
star
16

go-keyring

Cross-platform keyring interface for Go
Go
689
star
17

gin-oauth2

Middleware for Gin Framework users who also want to use OAuth2
Go
556
star
18

zappr

An agent that enforces guidelines for your GitHub repositories
JavaScript
543
star
19

pg_view

Get a detailed, real-time view of your PostgreSQL database and system metrics
Python
488
star
20

engineering-principles

Our guidelines for building new applications and managing legacy systems
363
star
21

gulp-check-unused-css

A build tool for checking your HTML templates for unused CSS classes
CSS
359
star
22

zmon

Real-time monitoring of critical metrics & KPIs via elegant dashboards, Grafana3 visualizations & more
Shell
355
star
23

expan

Open-source Python library for statistical analysis of randomised control trials (A/B tests)
Python
325
star
24

PGObserver

A battle-tested, flexible & comprehensive monitoring solution for your PostgreSQL databases
Python
315
star
25

riptide

Client-side response routing for Spring
Java
285
star
26

jackson-datatype-money

Extension module to properly support datatypes of javax.money
Java
240
star
27

grafter

Grafter is a library to configure and wire Scala applications
Scala
240
star
28

opentracing-toolbox

Best-of-breed OpenTracing utilities, instrumentations and extensions
Java
178
star
29

elm-street-404

A fun WebGL game built with Elm
Elm
176
star
30

tokens

Java library for conveniently verifying and storing OAuth 2.0 service access tokens
Java
169
star
31

innkeeper

Simple route management API for Skipper
Scala
166
star
32

public-presentations

List of public talks by Zalando Tech: meetup presentations, recorded conference talks, slides
165
star
33

python-nsenter

Enter kernel namespaces from Python
Python
139
star
34

dress-code

The official style guide and framework for all Zalando Brand Solutions products
CSS
129
star
35

faux-pas

A library that simplifies error handling for Functional Programming in Java
Java
128
star
36

beard

A lightweight, logicless templating engine, written in Scala and inspired by Mustache
Scala
121
star
37

friboo

Utility library for writing microservices in Clojure, with support for Swagger and OAuth
Clojure
117
star
38

spring-cloud-config-aws-kms

Spring Cloud Config add-on that provides encryption via AWS KMS
Java
99
star
39

zalando.github.io

Open Source Documentation and guidelines for Zalando developers
HTML
80
star
40

failsafe-actuator

Endpoint library for the failsafe framework
Java
53
star
41

package-build

A toolset for building system packages using Docker and fpm-cookery
Ruby
35
star
42

ghe-backup

Github Enterprise backup at ZalandoTech (Kubernetes, AWS, Docker)
Shell
30
star
43

rds-health

discover anomalies, performance issues and optimization within AWS RDS
Go
18
star
44

backstage-plugin-api-linter

API Linter is a quality assurance tool that checks the compliance of API's specifications to Zalando's API rules.
TypeScript
12
star
45

.github

Standard github health files
1
star