Problem Spring Web is a library 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
Spring Web MVC'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
.
- let's you choose traits à la carte
- favors composition over inheritance
- 15+ useful advice traits built in
Add the following dependency to your project:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
<version>${problem-spring-web.version}</version>
</dependency>
Make sure you register the required modules with your ObjectMapper:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new ProblemModule());
}
The following table shows all built-in advice traits:
You're free to use them individually or in groups. Future versions of this library may add additional traits to groups. A typical usage would look like this:
@ControllerAdvice
class ExceptionHandling implements ProblemHandling {
}
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) {
return ..;
}
@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/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/json
{
"title": "Method Not Allowed",
"status": 405,
"detail": "POST not supported"
}
If you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.
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.