• Stars
    star
    1,031
  • Rank 44,680 (Top 0.9 %)
  • Language
    Java
  • License
    MIT License
  • Created about 9 years ago
  • Updated 6 months ago

Reviews

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

Repository Details

A library for handling Problems in Spring Web MVC

Problems for Spring MVC and Spring WebFlux

Stability: Sustained Build Status Coverage Status Code Quality Release License

Problem Spring Web is a set of libraries that makes it easy to produce application/problem+json responses from a Spring application. It fills a niche, in that it connects the Problem library and either Spring Web MVC's exception handling or Spring WebFlux's exception handling so that they work seamlessly together, while requiring minimal additional developer effort. In doing so, it aims to perform a small but repetitive task — once and for all.

The way this library works is based on what we call advice traits. An advice trait is a small, reusable @ExceptionHandler implemented as a default method placed in a single method interface. Those advice traits can be combined freely and don't require to use a common base class for your @ControllerAdvice.

🔎 Please check out Baeldung: A Guide to the Problem Spring Web Library for a detailed introduction!

Features

  • lets you choose traits à la carte
  • favors composition over inheritance
  • ~20 useful advice traits built in
  • Spring MVC and Spring WebFlux support
  • Spring Security support
  • customizable processing

Dependencies

  • Java 17
  • Any build tool using Maven Central, or direct download
  • Servlet Container for problem-spring-web or
  • Reactive, non-blocking runtime for problem-spring-webflux
  • Spring 6 (or Spring Boot 3) users may use version >= 0.28.0
  • Spring 5 (or Spring Boot 2) users may use version 0.27.0
  • Spring 4 (or Spring Boot 1.5) users may use version 0.23.0
  • Spring Security 5 (optional)
  • Failsafe 2.3.3 (optional)

Installation and Configuration

Customization

The problem handling process provided by AdviceTrait is built in a way that allows for customization whenever the need arises. All of the following aspects (and more) can be customized by implementing the appropriate advice trait interface:

Aspect Method(s) Default
Creation AdviceTrait.create(..)
Logging AdviceTrait.log(..) 4xx as WARN, 5xx as ERROR including stack trace
Content Negotiation AdviceTrait.negotiate(..) application/json, application/*+json, application/problem+json and application/x.problem+json
Fallback AdviceTrait.fallback(..) application/problem+json
Post-Processing AdviceTrait.process(..) n/a

The following example customizes the MissingServletRequestParameterAdviceTrait by adding a parameter extension field to the Problem:

@ControllerAdvice
public class MissingRequestParameterExceptionHandler implements MissingServletRequestParameterAdviceTrait {
    @Override
    public ProblemBuilder prepare(Throwable throwable, StatusType status, URI type) {
        var exception = (MissingServletRequestParameterException) throwable;
        return Problem.builder()
                      .withTitle(status.getReasonPhrase())
                      .withStatus(status)
                      .withDetail(exception.getMessage())
                      .with("parameter", exception.getParameterName());
    }
}

Usage

Assuming there is a controller like this:

@RestController
@RequestMapping("/products")
class ProductsResource {

    @RequestMapping(method = GET, value = "/{productId}", produces = APPLICATION_JSON_VALUE)
    public Product getProduct(String productId) {
        // TODO implement
        return null;
    }

    @RequestMapping(method = PUT, value = "/{productId}", consumes = APPLICATION_JSON_VALUE)
    public Product updateProduct(String productId, Product product) {
        // TODO implement
        throw new UnsupportedOperationException();
    }

}

The following HTTP requests will produce the corresponding response respectively:

GET /products/123 HTTP/1.1
Accept: application/xml
HTTP/1.1 406 Not Acceptable
Content-Type: application/problem+json

{
  "title": "Not Acceptable",
  "status": 406,
  "detail": "Could not find acceptable representation"
}
POST /products/123 HTTP/1.1
Content-Type: application/json

{}
HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Type: application/problem+json

{
  "title": "Method Not Allowed",
  "status": 405,
  "detail": "POST not supported"
}

Stack traces and causal chains

Before you continue, please read the section about Stack traces and causal chains in zalando/problem.

In case you want to enable stack traces, please configure your ProblemModule as follows:

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

Causal chains of problems are disabled by default, but can be overridden if desired:

@ControllerAdvice
class ExceptionHandling implements ProblemHandling {

    @Override
    public boolean isCausalChainsEnabled() {
        return true;
    }

}

Note Since you have full access to the application context at that point, you can externalize the configuration to your application.yml and even decide to reuse Spring's server.error.include-stacktrace property.

Enabling both features, causal chains and stacktraces, will yield:

{
  "title": "Internal Server Error",
  "status": 500,
  "detail": "Illegal State",
  "stacktrace": [
    "org.example.ExampleRestController.newIllegalState(ExampleRestController.java:96)",
    "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:91)"
  ],
  "cause": {
    "title": "Internal Server Error",
    "status": 500,
    "detail": "Illegal Argument",
    "stacktrace": [
      "org.example.ExampleRestController.newIllegalArgument(ExampleRestController.java:100)",
      "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:88)"
    ],
    "cause": {
      "title": "Internal Server Error",
      "status": 500,
      "detail": "Null Pointer",
      "stacktrace": [
        "org.example.ExampleRestController.newNullPointer(ExampleRestController.java:104)",
        "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:86)",
        "sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
        "sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)",
        "sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)",
        "java.lang.reflect.Method.invoke(Method.java:483)",
        "org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)",
        "org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)",
        "org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)",
        "org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)",
        "org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)",
        "org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)",
        "org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)",
        "org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)",
        "org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)",
        "org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)",
        "org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)",
        "org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)",
        "org.junit.runners.ParentRunner.run(ParentRunner.java:363)",
        "org.junit.runner.JUnitCore.run(JUnitCore.java:137)",
        "com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)",
        "com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)",
        "com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)"
      ]
    }
  }
}

Known Issues

Spring allows to restrict the scope of a @ControllerAdvice to a certain subset of controllers:

@ControllerAdvice(assignableTypes = ExampleController.class)
public final class ExceptionHandling implements ProblemHandling

By doing this you'll loose the capability to handle certain types of exceptions namely:

  • HttpRequestMethodNotSupportedException
  • HttpMediaTypeNotAcceptableException
  • HttpMediaTypeNotSupportedException
  • NoHandlerFoundException

We inherit this restriction from Spring and therefore recommend to use an unrestricted @ControllerAdvice.

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.

Credits and references

More Repositories

1

patroni

A template for PostgreSQL High Availability with Etcd, Consul, ZooKeeper, or Kubernetes
Python
6,267
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,088
star
4

restful-api-guidelines

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

zalenium

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

SwiftMonkey

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

logbook

An extensible Java library for HTTP request and response logging
Java
1,788
star
8

tailor

A streaming layout service for front-end microservices
JavaScript
1,728
star
9

tech-radar

Visualizing our technology choices
1,581
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,172
star
12

nakadi

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

zally

A minimalistic, simple-to-use API linter
Kotlin
903
star
14

problem

A Java library that implements application/problem+json
Java
869
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
580
star
18

zappr

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

pg_view

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

engineering-principles

Our guidelines for building new applications and managing legacy systems
376
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
316
star
25

riptide

Client-side response routing for Spring
Java
292
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
180
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

faux-pas

A library that simplifies error handling for Functional Programming in Java
Java
132
star
35

dress-code

The official style guide and framework for all Zalando Brand Solutions products
CSS
129
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
86
star
40

failsafe-actuator

Endpoint library for the failsafe framework
Java
52
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
26
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