coders-kitchen / problem-spring-web

A library for handling Problems in Spring Web MVC

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problems for Spring Web MVC

Build Status Coverage Status Javadoc Release Maven Central License

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

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

Dependencies

  • Java 8
  • Any build tool using Maven Central, or direct download
  • Servlet Container
  • Spring
  • Spring Security

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 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
├──SecurityAdviceTrait
│   ├──AccessDeniedAdviceTrait 403 Forbidden
│   └──AuthenticationAdviceTrait 401 Unauthorized
└──ValidationAdviceTrait
    ├──ConstraintViolationAdviceTrait 400 Bad Request
    └──MethodArgumentNotValidAdviceTrait 400 Bad Request

You're free to use them either 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 {

}

The NoHandlerFoundAdviceTrait in addition also requires the following configuration:

spring:
  resources:
    add-mappings: false
  mvc:
    throw-exception-if-no-handler-found: true

Security

The Spring Security integration requires an additional step:

@Import(SecurityProblemSupport.class)
public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProblemSupport problemSupport;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(problemSupport)
                .accessDeniedHandler(problemSupport);
    }

}

Customization

The problem handling process provided by AdviceTrait is built in a way that it allows for customization whenever the need arises. All of the following aspects can be overridden and tweaked:

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(..) 406 Not Acceptable, without a body
Post-Processing AdviceTrait.process(..) n/a

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] (https://github.com/zalando/problem#stack-traces-and-causal-chains) in [zalando/problem] (https://github.com/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 Issuess

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

About

A library for handling Problems in Spring Web MVC

License:MIT License


Languages

Language:Java 89.8%Language:Shell 6.1%Language:Batchfile 4.2%