All Projects → zalando → Problem Spring Web

zalando / Problem Spring Web

Licence: mit
A library for handling Problems in Spring Web MVC

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Problem Spring Web

Jbone
jbone基于Spring Cloud框架开发,旨在为中小企业提供稳定的微服务解决方案,为开发人员提供基础开发骨架,jbone包含微服务中所有常用组件,例如注册中心、服务管理、服务监控、JVM监控、内存分析、调用链跟踪、API网关等等。业务功能包括系统权限的统一管理、单点登录、CMS、电商平台、工作流平台、支付平台等等。
Stars: ✭ 961 (+51.1%)
Mutual labels:  microservice, spring-boot, spring
Hex Arch Kotlin Spring Boot
Reference JVM multi module project for a reactive micro service and lambda using a hexagonal architecture, DDD, Kotlin, Spring Boot, Quarkus, Lambda, Gradle.
Stars: ✭ 83 (-86.95%)
Mutual labels:  microservice, spring-boot, spring
Mini Platform
Mini-Platform致力于更简洁易用的轻量级微服务治理平台。
Stars: ✭ 45 (-92.92%)
Mutual labels:  microservice, spring-boot, spring
Html Pdf Service
LGPL V3. Java Spring Boot microservice with RESTful webconsole and service endpoints that convert HTML to PDF, optionally styling with CSS and templating with JSON using Flying Saucer, PDF Box and Jackson libraries. Available on Docker Hub.
Stars: ✭ 12 (-98.11%)
Mutual labels:  microservice, json, spring-boot
Quickperf
QuickPerf is a testing library for Java to quickly evaluate and improve some performance-related properties
Stars: ✭ 231 (-63.68%)
Mutual labels:  microservice, spring-boot, spring
Spring Cloud Study
开源书《跟我学Spring Cloud》的配套代码。讨论QQ群:731548893
Stars: ✭ 1,036 (+62.89%)
Mutual labels:  microservice, spring-boot, spring
Web Development Interview With Java
Java 开发相关技术栈(大中厂)高频面试问题收录。
Stars: ✭ 69 (-89.15%)
Mutual labels:  microservice, spring-boot, spring
Awesome Backend Architecture
后端开发常用技术框架、数据库、开源中间件、微服务、系统架构集合。
Stars: ✭ 114 (-82.08%)
Mutual labels:  microservice, spring-boot, spring
Spring Microservice Sample
Spring Boot based Mircoservice sample
Stars: ✭ 199 (-68.71%)
Mutual labels:  microservice, spring-boot, spring
Gemini
Model Driven REST framework to automatically generate CRUD APIs
Stars: ✭ 138 (-78.3%)
Mutual labels:  microservice, spring-boot, spring
Micro Company
Rest-full, Hipermedia-based distributed application. Spring boot & cloud. Angular. CQRS. Eventsourcing. Axonframework. Microservices. Docker. CloudFoundry
Stars: ✭ 307 (-51.73%)
Mutual labels:  microservice, spring-boot, spring
Istio By Example Java
A collection of examples of using Istio with Java applications.
Stars: ✭ 242 (-61.95%)
Mutual labels:  microservice, spring-boot, spring
Trampoline
Admin Spring Boot Locally
Stars: ✭ 325 (-48.9%)
Mutual labels:  microservice, spring-boot, spring
Im
IM server based on netty. Provides a client jar. Integrate with your own login system.基于netty实现的IM服务端,提供客户端jar包,可集成自己的登录系统
Stars: ✭ 490 (-22.96%)
Mutual labels:  spring-boot, spring
Sts4
The next generation of tooling for Spring Boot, including support for Cloud Foundry manifest files, Concourse CI pipeline definitions, BOSH deployment manifests, and more... - Available for Eclipse, Visual Studio Code, and Theia
Stars: ✭ 490 (-22.96%)
Mutual labels:  spring-boot, spring
Spring Cloud Commons
Common classes used in different Spring Cloud implementations
Stars: ✭ 493 (-22.48%)
Mutual labels:  spring-boot, spring
Getty
a netty like asynchronous network I/O library based on tcp/udp/websocket; a bidirectional RPC framework based on JSON/Protobuf; a microservice framework based on zookeeper/etcd
Stars: ✭ 532 (-16.35%)
Mutual labels:  microservice, json
Spring Cloud Security
Security concerns for distributed applications implemented in Spring
Stars: ✭ 488 (-23.27%)
Mutual labels:  spring-boot, spring
Java Interview Question
🔥Java面试题集中营,做了一些解答及相关知识点整理🔥
Stars: ✭ 531 (-16.51%)
Mutual labels:  spring-boot, spring
Springboot Jwt Starter
A Spring Boot JWT starter kit for stateless and token-based authentication apps.
Stars: ✭ 538 (-15.41%)
Mutual labels:  spring-boot, spring

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 8
  • 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 5
    • 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].