SkillAgentSearch skills...

Problem

A Java library that implements application/problem+json

Install / Use

/learn @zalando/Problem
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

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 pr

Related Skills

View on GitHub
GitHub Stars943
CategoryDevelopment
Updated18d ago
Forks95

Languages

Java

Security Score

100/100

Audited on Mar 11, 2026

No findings