/problem-spring-web

Handling Problems in Spring Web MVC

Primary LanguageJavaApache License 2.0Apache-2.0

Problems for Spring Web MVC

Build Status Coverage Status Release Maven Central

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.

Features

  • let's you choose traits à la carte
  • favors composition over inheritance
  • 15+ useful advice traits built in

Installation

Add the following dependency to your project:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>problem-spring-web</artifactId>
    <version>${problem-spring-web.version}</version>
</dependency>

Configuration

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:

Advice Trait Produces
ProblemHandling
├──GeneralAdviceTrait
│   ├──ProblemAdviceTrait depends
│   ├──ThrowableAdviceTrait 500 Internal Server Error
│   └── UnsupportedOperationAdviceTrait 501 Not Implemented
├──HttpAdviceTrait
│   ├──MethodNotAllowedAdviceTrait 405 Method Not Allowed
│   ├──NotAcceptableAdviceTrait 406 Not Acceptable
│   └──UnsupportedMediaTypeAdviceTrait 415 Unsupported Media Type
├──IOAdviceTrait
│   ├──MessageNotReadableAdviceTrait 400 Bad Request
│   ├──MultipartAdviceTrait 400 Bad Request
│   └──TypeMistmatchAdviceTrait 400 Bad Request
├──RoutingAdviceTrait
│   ├──MissingServletRequestParameterAdviceTrait 400 Bad Request
│   ├──MissingServletRequestPartAdviceTrait 400 Bad Request
│   ├──NoHandlerFoundAdviceTrait 404 Not Found
│   ├──NoSuchRequestHandlingMethodAdviceTrait 404 Not Found
│   └──ServletRequestBindingAdviceTrait 400 Bad Request
└──ValidationAdviceTrait
    ├──ConstraintViolationAdviceTrait 422 Unprocessable Entity
    └──MethodArgumentNotValidAdviceTrait 422 Unprocessable Entity

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 {

}

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) {
        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"
}

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