Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Problem Spring Web
https://github.com/zalando/problem-spring-web
Admin
A library for handling Problems in Spring Web MVC
Tokens:
81,616
Snippets:
595
Trust Score:
8.3
License:
MIT
Update:
13 hours ago
Context
Chat
Benchmark
51.6
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### SpringAdviceTrait usage example Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Shows a controller advice implementing SpringAdviceTrait and a direct call to create with HttpStatus.I_AM_A_TEAPOT. ```java @ControllerAdvice public class ExceptionHandling implements SpringAdviceTrait { // HttpStatus-based handlers available } // calling from code: adviceTrait.create(HttpStatus.I_AM_A_TEAPOT, exception, webRequest); ``` -------------------------------- ### Implementing SecurityAdviceTrait with ProblemHandling Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-security.md Example of a controller advice class that implements both ProblemHandling and SecurityAdviceTrait to enable security-related exception handling. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, SecurityAdviceTrait { } ``` -------------------------------- ### Usage example with ProblemHandling and OpenApiValidationAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-validation-traits.md Shows how to combine ProblemHandling and OpenApiValidationAdviceTrait in a @ControllerAdvice class to enable OpenAPI validation error handling. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, OpenApiValidationAdviceTrait { } ``` -------------------------------- ### Usage example for UnsupportedOperationAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-general-traits.md Shows a controller method that throws UnsupportedOperationException, resulting in a 501 Not Implemented response with content type application/problem+json. ```java @RequestMapping(method = PUT, value = "/{productId}", consumes = APPLICATION_JSON_VALUE) public Product updateProduct(String productId, Product product) { throw new UnsupportedOperationException(); } // -> HTTP/1.1 501 Not Implemented, application/problem+json ``` -------------------------------- ### Example JSON response for missing request parameter Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-routing-traits.md Example response body returned when a required request parameter is missing. Shows the Problem format with title, status, and detail. ```json { "title": "Bad Request", "status": 400, "detail": "Required request parameter 'productId' is not present" } ``` -------------------------------- ### Custom advice implementation using CustomAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-problemhandling.md Example of implementing CustomAdviceTrait with a custom @ExceptionHandler. Note that calling create(..) requires also implementing AdviceTrait; CustomAdviceTrait alone does not provide it. ```java @ControllerAdvice public class MyAdvice implements CustomAdviceTrait { @ExceptionHandler public ResponseEntity<Problem> handleMyException(MyException e, NativeWebRequest request) { return create(Status.BAD_REQUEST, e, request); // requires also implementing AdviceTrait } } ``` -------------------------------- ### Usage example with ExceptionHandling class Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-network-traits.md Example from the README showing how to use CircuitBreakerOpenAdviceTrait in a @ControllerAdvice class. The class implements ProblemHandling and CircuitBreakerOpenAdviceTrait. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, CircuitBreakerOpenAdviceTrait { } ``` -------------------------------- ### Usage example for TypeMismatchAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-io-traits.md Shows a GET request with a type mismatch (page=abc for an Integer parameter) and the resulting 400 Bad Request response with detail from TypeMismatchException. ```http // GET /products?page=abc where page is Integer // -> 400 Bad Request with detail from TypeMismatchException ``` -------------------------------- ### Sample ProductsResource controller Source: https://github.com/zalando/problem-spring-web/blob/main/README.md A Spring REST controller with GET and PUT endpoints for products. The GET method returns null (TODO), and the PUT method throws UnsupportedOperationException, which will be handled by the problem library. ```java @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(); } } ``` -------------------------------- ### POST request example Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-http-traits.md Example HTTP request that triggers a 405 Method Not Allowed response. Used to illustrate the behavior of the MethodNotAllowedAdviceTrait. ```http POST /products/123 HTTP/1.1 Content-Type: application/json ``` -------------------------------- ### Violation usage example Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-violations.md Shows how to create a Violation instance and access its field and message values. ```java import org.zalando.problem.violations.Violation; Violation v = new Violation("name", "must not be null"); v.getField(); // "name" v.getMessage(); // "must not be null" ``` -------------------------------- ### Usage example for ProblemAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-general-traits.md Shows how to use ProblemAdviceTrait in a @ControllerAdvice class. Throwing ThrowableProblem subclasses like ConstraintViolationProblem will render Problem JSON. ```java @ControllerAdvice public class ExceptionHandling implements ProblemAdviceTrait { } // throwing org.zalando.problem.ThrowableProblem subclasses now renders Problem JSON throw new ConstraintViolationProblem(Status.BAD_REQUEST, violations); ``` -------------------------------- ### Controller advice using ProblemHandling for 415 Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-http-traits.md Example of a controller advice that implements ProblemHandling to enable the UnsupportedMediaTypeAdviceTrait. Sending a POST with Content-Type: application/xml to a JSON-only endpoint results in a 415 response with an Accept header listing supported media types. ```java @ControllerAdvice public class ExceptionHandling implements ProblemHandling { } // POST with Content-Type: application/xml to a JSON-only endpoint // -> 415, Accept: application/json, application/*+json ``` -------------------------------- ### HttpStatusAdapter usage example Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-common.md Shows how to wrap HttpStatus.GONE with HttpStatusAdapter and retrieve the status code (410) and reason phrase ("Gone"). Requires imports from Spring and the problem-spring-common package. ```java import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; import org.zalando.problem.spring.common.HttpStatusAdapter; StatusType status = new HttpStatusAdapter(HttpStatus.GONE); int code = status.getStatusCode(); // 410 String reason = status.getReasonPhrase(); // "Gone" ``` -------------------------------- ### Example output JSON for circuit breaker open Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-network-traits.md The JSON response produced when the circuit breaker is open, including a Retry-After header. ```json { "title": "Service Unavailable", "status": 503 } ``` -------------------------------- ### Usage example for ResponseStatusAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-general-traits.md Shows how to apply the trait by implementing ProblemHandling in a @ControllerAdvice class. Throwing a ResponseStatusException with HttpStatus.NOT_FOUND results in a 404 response with title 'Not Found'. ```java @ControllerAdvice public class ExceptionHandling implements ProblemHandling { } // in a controller: throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found"); // -> 404 with title "Not Found" ``` -------------------------------- ### Usage example: ExceptionHandling with isCausalChainsEnabled and process overrides Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-common.md Shows how to implement ProblemHandling and override isCausalChainsEnabled to enable causal chains, and process to add a correlation id header to every problem response. ```java @ControllerAdvice public class ExceptionHandling implements ProblemHandling { @Override public boolean isCausalChainsEnabled() { return true; } @Override public ResponseEntity<Problem> process(ResponseEntity<Problem> entity) { // e.g. add a correlation id header to every problem response return ResponseEntity .status(entity.getStatusCode()) .headers(entity.getHeaders()) .body(entity.getBody()); } } ``` -------------------------------- ### Example problem JSON with stack traces and causal chains Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Shows the JSON output when both stack traces and causal chains are enabled. The response includes a stacktrace array and nested cause objects, each with their own stacktrace. ```yaml { "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)" ] } } } ``` -------------------------------- ### Usage example for ConstraintViolationProblem Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-violations.md Shows how to create a ConstraintViolationProblem with Status.BAD_REQUEST and a list of violations. The getTitle() returns "Constraint Violation", getType() returns the default type URI, and getViolations() returns the unmodifiable list. ```java import org.zalando.problem.Status; import org.zalando.problem.violations.Violation; import org.zalando.problem.violations.ConstraintViolationProblem; List<Violation> violations = List.of(new Violation("name", "must not be null")); ConstraintViolationProblem problem = new ConstraintViolationProblem(Status.BAD_REQUEST, violations); problem.getTitle(); // "Constraint Violation" problem.getType(); // https://zalando.github.io/problem/constraint-violation problem.getViolations(); ``` -------------------------------- ### HTTP request with Accept header causing 406 Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-http-traits.md Example request that triggers the NotAcceptableAdviceTrait handler. Sending GET /products/123 with Accept: application/xml when no XML representation is available results in a 406 response. ```http GET /products/123 HTTP/1.1 Accept: application/xml ``` -------------------------------- ### AdviceTrait.create(Throwable, Problem, ServerWebExchange, HttpHeaders) - Terminal Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Terminal implementation of the create method. Builds the response using a reactive pipeline: log, store ERROR_EXCEPTION on 500, negotiate content type, fallback, and process. ```APIDOC ## create(Throwable, Problem, ServerWebExchange, HttpHeaders) - Terminal ### Description Terminal implementation of the create method. Builds the response using a reactive pipeline: log, store ERROR_EXCEPTION on 500, negotiate content type, fallback, and process. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final Throwable throwable, final Problem problem, final ServerWebExchange request, final HttpHeaders headers)` ### Parameters - **throwable** (Throwable) - Required - The throwable to log and store as error exception. - **problem** (Problem) - Required - The problem to use as the response body. - **request** (ServerWebExchange) - Required - The current server web exchange. - **headers** (HttpHeaders) - Required - HTTP headers to include in the response. ### Behavior - Determines HTTP status from problem.getStatus() or defaults to INTERNAL_SERVER_ERROR. - Logs the throwable and problem. - On success, if status is 500, stores the throwable in request attributes under ERROR_EXCEPTION. - Negotiates content type; if empty, uses fallback. - Builds ResponseEntity with status, headers, content type, and problem body. - Processes the entity. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### AdviceTrait.create(ThrowableProblem, ServerWebExchange, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response from a ThrowableProblem with explicit headers. Delegates with the problem as both throwable and problem. ```APIDOC ## create(ThrowableProblem, ServerWebExchange, HttpHeaders) ### Description Creates a Problem response from a ThrowableProblem with explicit headers. Delegates with the problem as both throwable and problem. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final ThrowableProblem problem, final ServerWebExchange request, final HttpHeaders headers)` ### Parameters - **problem** (ThrowableProblem) - Required - The problem to use as both throwable and problem. - **request** (ServerWebExchange) - Required - The current server web exchange. - **headers** (HttpHeaders) - Required - HTTP headers to include in the response. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### AdviceTrait.create(Throwable, Problem, ServerWebExchange) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response from a Throwable and a Problem. Adds empty HttpHeaders and delegates to the terminal overload. ```APIDOC ## create(Throwable, Problem, ServerWebExchange) ### Description Creates a Problem response from a Throwable and a Problem. Adds empty HttpHeaders and delegates to the terminal overload. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final Throwable throwable, final Problem problem, final ServerWebExchange request)` ### Parameters - **throwable** (Throwable) - Required - The throwable to log and store as error exception. - **problem** (Problem) - Required - The problem to use as the response body. - **request** (ServerWebExchange) - Required - The current server web exchange. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### AdviceTrait.create(ThrowableProblem, ServerWebExchange) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response from a ThrowableProblem. Adds empty HttpHeaders and delegates to the overload with headers. ```APIDOC ## create(ThrowableProblem, ServerWebExchange) ### Description Creates a Problem response from a ThrowableProblem. Adds empty HttpHeaders and delegates to the overload with headers. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final ThrowableProblem problem, final ServerWebExchange request)` ### Parameters - **problem** (ThrowableProblem) - Required - The problem to use as both throwable and problem. - **request** (ServerWebExchange) - Required - The current server web exchange. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### Override isCausalChainsEnabled() in @ControllerAdvice Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/configuration.md Override the isCausalChainsEnabled() hook to enable causal chains. The default is false. This example is from the root README. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling { @Override public boolean isCausalChainsEnabled() { return true; } } ``` -------------------------------- ### AdviceTrait.create(Throwable, ServerWebExchange) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response from a Throwable. Converts the throwable to a Problem using toProblem(throwable) and delegates to the terminal overload. ```APIDOC ## create(Throwable, ServerWebExchange) ### Description Creates a Problem response from a Throwable. Converts the throwable to a Problem using toProblem(throwable) and delegates to the terminal overload. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final Throwable throwable, final ServerWebExchange request)` ### Parameters - **throwable** (Throwable) - Required - The throwable to convert to a Problem. - **request** (ServerWebExchange) - Required - The current server web exchange. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### Call create directly from application code Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Shows how to invoke create(..) directly, producing an HTTP 400 response with Content-Type application/problem+json. ```java import org.zalando.problem.Status; import org.zalando.problem.Problem; ResponseEntity<Problem> response = adviceTrait.create(Status.BAD_REQUEST, new IllegalStateException("nope"), webRequest); // HTTP 400, Content-Type: application/problem+json ``` -------------------------------- ### AdviceTrait.create(ThrowableProblem, NativeWebRequest, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> from a ThrowableProblem with custom HTTP headers. ```APIDOC ## AdviceTrait.create(ThrowableProblem, NativeWebRequest, HttpHeaders) ### Description Creates a `ResponseEntity<Problem>` from a `ThrowableProblem` with custom HTTP headers. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request, final HttpHeaders headers) ``` ### Parameters - **problem** (`org.zalando.problem.ThrowableProblem`) - Required - The problem to be returned - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request - **headers** (`org.springframework.http.HttpHeaders`) - Required - HTTP headers to include in the response ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### SecurityExceptionHandler implementing SecurityAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-security.md A @ControllerAdvice that implements SecurityAdviceTrait to enable problem rendering for security exceptions. This is used together with the SecurityConfiguration example. ```java @ControllerAdvice public class SecurityExceptionHandler implements SecurityAdviceTrait { } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, ServerWebExchange, HttpHeaders, URI) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response with explicit status, headers, and type URI. Delegates to the terminal overload with a Problem created from the throwable, status, and type. ```APIDOC ## create(StatusType, Throwable, ServerWebExchange, HttpHeaders, URI) ### Description Creates a Problem response with explicit status, headers, and type URI. Delegates to the terminal overload with a Problem created from the throwable, status, and type. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final StatusType status, final Throwable throwable, final ServerWebExchange request, final HttpHeaders headers, final URI type)` ### Parameters - **status** (StatusType) - Required - The HTTP status type. - **throwable** (Throwable) - Required - The throwable to convert to a Problem. - **request** (ServerWebExchange) - Required - The current server web exchange. - **headers** (HttpHeaders) - Required - HTTP headers to include in the response. - **type** (URI) - Required - The type URI for the Problem. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### AdviceTrait.create(ThrowableProblem, NativeWebRequest) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> from a ThrowableProblem and the incoming request. ```APIDOC ## AdviceTrait.create(ThrowableProblem, NativeWebRequest) ### Description Creates a `ResponseEntity<Problem>` from a `ThrowableProblem` and the incoming request. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request) ``` ### Parameters - **problem** (`org.zalando.problem.ThrowableProblem`) - Required - The problem to be returned - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### JSON response body for 406 Not Acceptable Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-http-traits.md Example response body returned by the NotAcceptableAdviceTrait handler. Contains title, status, and detail fields. ```json { "title": "Not Acceptable", "status": 406, "detail": "Could not find acceptable representation" } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, ServerWebExchange, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response with explicit status and headers. Delegates to the terminal overload with a Problem created from the throwable and status. ```APIDOC ## create(StatusType, Throwable, ServerWebExchange, HttpHeaders) ### Description Creates a Problem response with explicit status and headers. Delegates to the terminal overload with a Problem created from the throwable and status. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final StatusType status, final Throwable throwable, final ServerWebExchange request, final HttpHeaders headers)` ### Parameters - **status** (StatusType) - Required - The HTTP status type. - **throwable** (Throwable) - Required - The throwable to convert to a Problem. - **request** (ServerWebExchange) - Required - The current server web exchange. - **headers** (HttpHeaders) - Required - HTTP headers to include in the response. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### AdviceTrait.create(Throwable, Problem, NativeWebRequest, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Terminal overload that creates a ResponseEntity<Problem> with an arbitrary Problem body and custom HTTP headers. ```APIDOC ## AdviceTrait.create(Throwable, Problem, NativeWebRequest, HttpHeaders) ### Description Terminal overload that creates a `ResponseEntity<Problem>` with an arbitrary `Problem` body and custom HTTP headers. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request, final HttpHeaders headers) ``` ### Parameters - **throwable** (`Throwable`) - Required - Exception being caught - **problem** (`org.zalando.problem.Problem`) - Required - The problem body to return - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request - **headers** (`org.springframework.http.HttpHeaders`) - Required - HTTP headers to include in the response ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### Usage example for MessageNotReadableAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-io-traits.md Shows a POST request with invalid JSON body and the resulting 400 Bad Request response with application/problem+json content type. ```http // sends invalid JSON body: POST /products HTTP/1.1 Content-Type: application/json { "name": // -> 400 Bad Request, application/problem+json ``` -------------------------------- ### Serialized JSON shape of ConstraintViolationProblem Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-violations.md Example JSON output when the problem is serialized with the Jackson module registered. Shows the type, title, status, and violations array. ```json { "type": "https://zalando.github.io/problem/constraint-violation", "title": "Constraint Violation", "status": 400, "violations": [ { "field": "name", "message": "must not be null" } ] } ``` -------------------------------- ### AdviceTrait.create(Throwable, Problem, NativeWebRequest) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> with an arbitrary Problem body independent of the throwable. ```APIDOC ## AdviceTrait.create(Throwable, Problem, NativeWebRequest) ### Description Creates a `ResponseEntity<Problem>` with an arbitrary `Problem` body independent of the throwable. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request) ``` ### Parameters - **throwable** (`Throwable`) - Required - Exception being caught - **problem** (`org.zalando.problem.Problem`) - Required - The problem body to return - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### Usage example for MethodArgumentNotValidAdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-validation-traits.md Shows a controller method with @Valid @RequestBody that triggers the advice when validation fails, producing a 400 response with a constraint violation problem body. ```java public class Product { @NotNull private String name; } @PostMapping("/products") public Product create(@Valid @RequestBody Product product) { ... } // -> 400 with: // { "type": "https://zalando.github.io/problem/constraint-violation", // "title": "Constraint Violation", "status": 400, "violations": [ ... ] } ``` -------------------------------- ### 405 Method Not Allowed response Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-http-traits.md Example JSON response body for a 405 error, including the Allow header value. This is the output produced by the MethodNotAllowedAdviceTrait when the request method is not supported. ```json { "title": "Method Not Allowed", "status": 405, "detail": "POST not supported", "allow": ["GET"] } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, NativeWebRequest, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> with explicit status and custom HTTP headers. ```APIDOC ## AdviceTrait.create(StatusType, Throwable, NativeWebRequest, HttpHeaders) ### Description Creates a `ResponseEntity<Problem>` with explicit status and custom HTTP headers. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers) ``` ### Parameters - **status** (`org.zalando.problem.StatusType`) - Required - Explicit status type - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request - **headers** (`org.springframework.http.HttpHeaders`) - Required - HTTP headers to include in the response ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### create(ThrowableProblem, NativeWebRequest, HttpHeaders) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Passes the same ThrowableProblem both as throwable (used for logging and ERROR_EXCEPTION) and as problem. ```java default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request, final HttpHeaders headers) { return create(problem, problem, request, headers); } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, ServerWebExchange, URI) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response with an explicit status and type URI. Adds empty HttpHeaders and delegates to the overload with headers and type. ```APIDOC ## create(StatusType, Throwable, ServerWebExchange, URI) ### Description Creates a Problem response with an explicit status and type URI. Adds empty HttpHeaders and delegates to the overload with headers and type. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final StatusType status, final Throwable throwable, final ServerWebExchange request, final URI type)` ### Parameters - **status** (StatusType) - Required - The HTTP status type. - **throwable** (Throwable) - Required - The throwable to convert to a Problem. - **request** (ServerWebExchange) - Required - The current server web exchange. - **type** (URI) - Required - The type URI for the Problem. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### Restricted @ControllerAdvice Example Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Shows how to restrict a @ControllerAdvice to a specific controller using assignableTypes. This causes loss of handling for HttpRequestMethodNotSupportedException, HttpMediaTypeNotAcceptableException, HttpMediaTypeNotSupportedException, and NoHandlerFoundException. Recommended to use an unrestricted @ControllerAdvice instead. ```java @ControllerAdvice(assignableTypes = ExampleController.class) public final class ExceptionHandling implements ProblemHandling ``` -------------------------------- ### HTTP request and response for 406 Not Acceptable Source: https://github.com/zalando/problem-spring-web/blob/main/README.md A GET request with Accept: application/xml to /products/123 results in a 406 Not Acceptable response with a problem+json body. The response includes title, status, and detail fields. ```http GET /products/123 HTTP/1.1 Accept: application/xml ``` ```http HTTP/1.1 406 Not Acceptable Content-Type: application/problem+json { "title": "Not Acceptable", "status": 406, "detail": "Could not find acceptable representation" } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, NativeWebRequest, HttpHeaders, URI) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> with explicit status, custom headers, and a custom problem type URI. ```APIDOC ## AdviceTrait.create(StatusType, Throwable, NativeWebRequest, HttpHeaders, URI) ### Description Creates a `ResponseEntity<Problem>` with explicit status, custom headers, and a custom problem `type` URI. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers, final URI type) ``` ### Parameters - **status** (`org.zalando.problem.StatusType`) - Required - Explicit status type - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request - **headers** (`org.springframework.http.HttpHeaders`) - Required - HTTP headers to include in the response - **type** (`java.net.URI`) - Required - Overrides the problem `type` URI ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### Customize MissingServletRequestParameterAdviceTrait with parameter extension Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Override the prepare method to add a 'parameter' extension field to the Problem. Casts the throwable to MissingServletRequestParameterException and uses its parameter name. This example is for Spring MVC's @ControllerAdvice. ```java @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()); } } ``` -------------------------------- ### create(StatusType, Throwable, NativeWebRequest, HttpHeaders, URI) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Converts the throwable with the given status and type URI via toProblem(throwable, status, type) and delegates to the terminal create(throwable, problem, request, headers) overload. ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers, final URI type) { return create(throwable, toProblem(throwable, status, type), request, headers); } ``` -------------------------------- ### Add problem-spring-web-starter dependency (Spring Boot) Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Add this Maven dependency to your project to get a default working configuration with problem-spring-web. The autoconfiguration will handle all problems and Spring Security problems if Spring Security is detected. ```xml <dependency> <groupId>org.zalando</groupId> <artifactId>problem-spring-web-starter</artifactId> <version>${problem-spring-web.version}</version> </dependency> ``` -------------------------------- ### create(StatusType, Throwable, NativeWebRequest, HttpHeaders) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Converts the throwable with the given status via toProblem(throwable, status) and delegates to the terminal create(throwable, problem, request, headers) overload. ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final HttpHeaders headers) { return create(throwable, toProblem(throwable, status), request, headers); } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, NativeWebRequest, URI) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> with explicit status and a custom problem type URI. ```APIDOC ## AdviceTrait.create(StatusType, Throwable, NativeWebRequest, URI) ### Description Creates a `ResponseEntity<Problem>` with explicit status and a custom problem `type` URI. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request, final URI type) ``` ### Parameters - **status** (`org.zalando.problem.StatusType`) - Required - Explicit status type - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request - **type** (`java.net.URI`) - Required - Overrides the problem `type` URI ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### Terminal create(..) overload with reactive pipeline Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Terminal implementation of create(..) that builds a ResponseEntity<Problem> via a reactive pipeline: logs, stores ERROR_EXCEPTION on 500, negotiates content type, falls back, and processes the entity. ```java default Mono<ResponseEntity<Problem>> create(final Throwable throwable, final Problem problem, final ServerWebExchange request, final HttpHeaders headers) { final HttpStatus status = HttpStatus.valueOf(Optional.ofNullable(problem.getStatus()) .orElse(Status.INTERNAL_SERVER_ERROR) .getStatusCode()); return log(throwable, problem, request, status) .doOnSuccess(it -> { if (status == HttpStatus.INTERNAL_SERVER_ERROR) { request.getAttributes().put(ERROR_EXCEPTION, throwable); } }) .then(Mono.justOrEmpty(negotiate(request))) .map(contentType -> ResponseEntity .status(status) .headers(headers) .contentType(contentType) .body(problem) ) .switchIfEmpty(fallback(throwable, problem, request, headers)) .flatMap(entity -> process(entity, request)); } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, NativeWebRequest) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> using an explicit StatusType for the problem status. ```APIDOC ## AdviceTrait.create(StatusType, Throwable, NativeWebRequest) ### Description Creates a `ResponseEntity<Problem>` using an explicit `org.zalando.problem.StatusType` for the problem status. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request) ``` ### Parameters - **status** (`org.zalando.problem.StatusType`) - Required - Explicit status type - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### AdviceTrait.create(Throwable, NativeWebRequest) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> from a Throwable and the incoming request. The status is derived from @ResponseStatus, ErrorResponse, or defaults to 500. ```APIDOC ## AdviceTrait.create(Throwable, NativeWebRequest) ### Description Creates a `ResponseEntity<Problem>` from a `Throwable` and the incoming request. The status is derived from `@ResponseStatus`/`ErrorResponse`/default 500. ### Method `create` ### Signature ```java default ResponseEntity<Problem> create(final Throwable throwable, final NativeWebRequest request) ``` ### Parameters - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`org.springframework.web.context.request.NativeWebRequest`) - Required - Incoming request ### Returns `ResponseEntity<org.zalando.problem.Problem>` ``` -------------------------------- ### HttpStatusAdapter Constructor Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-common.md Creates an HttpStatusAdapter from an HttpStatusCode. If the status is an HttpStatus, its reason phrase is captured. ```APIDOC ## HttpStatusAdapter Constructor ### Description Creates an HttpStatusAdapter from an HttpStatusCode. If the status is an HttpStatus, its reason phrase is captured. ### Method Constructor ### Parameters - **status** (org.springframework.http.HttpStatusCode) - Required - Status code to adapt; when it is an HttpStatus, the enum's reason phrase is captured. ### Usage Example ```java import org.springframework.http.HttpStatus; import org.zalando.problem.spring.common.HttpStatusAdapter; StatusType status = new HttpStatusAdapter(HttpStatus.GONE); ``` ``` -------------------------------- ### create(ThrowableProblem, NativeWebRequest) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Delegates to the overload that adds empty HttpHeaders. ```java default ResponseEntity<Problem> create(final ThrowableProblem problem, final NativeWebRequest request) { return create(problem, request, new HttpHeaders()); } ``` -------------------------------- ### create(Throwable, Problem, NativeWebRequest) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Allows supplying an arbitrary Problem body independent of the throwable. Delegates to the overload that adds empty HttpHeaders. ```java default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request) { return create(throwable, problem, request, new HttpHeaders()); } ``` -------------------------------- ### SpringAdviceTrait.create(HttpStatus, Throwable, NativeWebRequest) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> for the given HTTP status, throwable, and request, using default headers. ```APIDOC ## create(HttpStatus status, Throwable throwable, NativeWebRequest request) ### Description Creates a `ResponseEntity<Problem>` for the given HTTP status, throwable, and request, using default headers. ### Method create ### Signature `default ResponseEntity<Problem> create(HttpStatus status, Throwable throwable, NativeWebRequest request)` ### Parameters - **status** (`org.springframework.http.HttpStatus`) - Required - Spring HTTP status enum - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`NativeWebRequest`) - Required - Incoming request ### Returns `ResponseEntity<Problem>` ### Notes Equivalent to `create(status, throwable, request, new HttpHeaders())`. ### Usage Example ```java adviceTrait.create(HttpStatus.I_AM_A_TEAPOT, exception, webRequest); ``` ``` -------------------------------- ### SpringAdviceTrait interface with reactive problem creation methods Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Experimental interface for WebFlux. Provides default methods to create problems as Mono<ResponseEntity<Problem>>, accepting org.springframework.http.HttpStatus and converting it via HttpStatusAdapter. Identical shape to the servlet variant but reactive. ```java @API(status = EXPERIMENTAL) public interface SpringAdviceTrait extends AdviceTrait { default Mono<ResponseEntity<Problem>> create(final HttpStatus status, final Throwable throwable, final ServerWebExchange request) { return create(status, throwable, request, new HttpHeaders()); } default Mono<ResponseEntity<Problem>> create(final HttpStatus status, final Throwable throwable, final ServerWebExchange request, final HttpHeaders headers) { return create(toStatus(status), throwable, request, headers); } default ThrowableProblem toProblem(final Throwable throwable, final HttpStatus status) { return toProblem(throwable, toStatus(status)); } default StatusType toStatus(final HttpStatus status) { return new HttpStatusAdapter(status); } } ``` -------------------------------- ### create(StatusType, Throwable, NativeWebRequest) overload Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Uses the explicit org.zalando.problem.StatusType and delegates to the overload that adds empty HttpHeaders. ```java default ResponseEntity<Problem> create(final StatusType status, final Throwable throwable, final NativeWebRequest request) { return create(status, throwable, request, new HttpHeaders()); } ``` -------------------------------- ### AdviceTrait.create(StatusType, Throwable, ServerWebExchange) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-webflux.md Creates a Problem response with an explicit status type. Adds empty HttpHeaders and delegates to the overload with headers. ```APIDOC ## create(StatusType, Throwable, ServerWebExchange) ### Description Creates a Problem response with an explicit status type. Adds empty HttpHeaders and delegates to the overload with headers. ### Method create ### Signature `default Mono<ResponseEntity<Problem>> create(final StatusType status, final Throwable throwable, final ServerWebExchange request)` ### Parameters - **status** (StatusType) - Required - The HTTP status type. - **throwable** (Throwable) - Required - The throwable to convert to a Problem. - **request** (ServerWebExchange) - Required - The current server web exchange. ### Returns Mono<ResponseEntity<Problem>> - A reactive response entity containing the Problem. ``` -------------------------------- ### create method default implementation Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Default implementation of the create method. Resolves the HTTP status from the problem (defaulting to 500), logs the error, stores the throwable as a request attribute when status is 500, negotiates the content type, and falls back to a fallback response if negotiation fails. The fallback flushes a ServletServerHttpResponse to work around a Tomcat/Spring issue (zalando/problem-spring-web#84). ```java default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request, final HttpHeaders headers) { final HttpStatus status = HttpStatus.valueOf(Optional.ofNullable(problem.getStatus()) .orElse(Status.INTERNAL_SERVER_ERROR) .getStatusCode()); log(throwable, problem, request, status); if (status == HttpStatus.INTERNAL_SERVER_ERROR) { request.setAttribute(ERROR_EXCEPTION, throwable, SCOPE_REQUEST); } return process(negotiate(request).map(contentType -> ResponseEntity .status(status) .headers(headers) .contentType(contentType) .body(problem)) .orElseGet(throwingSupplier(() -> { /* Tomcat workaround: flushes ServletServerHttpResponse manually */ return fallback(throwable, problem, request, headers); })), request); } ``` -------------------------------- ### Add problem-spring-web and jackson-datatype-problem dependencies (WebMVC) Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Use these dependencies when not using the starter module. They are required for plain WebMVC projects. ```xml <dependency> <groupId>org.zalando</groupId> <artifactId>problem-spring-web</artifactId> <version>${problem-spring-web.version}</version> </dependency> <dependency> <groupId>org.zalando</groupId> <artifactId>jackson-datatype-problem</artifactId> <version>0.27.1</version> </dependency> ``` -------------------------------- ### SpringAdviceTrait.create(HttpStatus, Throwable, NativeWebRequest, HttpHeaders) Source: https://github.com/zalando/problem-spring-web/blob/main/_autodocs/api-reference/problem-spring-web-advicetrait.md Creates a ResponseEntity<Problem> with custom headers, delegating to the core create method with a converted StatusType. ```APIDOC ## create(HttpStatus status, Throwable throwable, NativeWebRequest request, HttpHeaders headers) ### Description Creates a `ResponseEntity<Problem>` with custom headers, delegating to the core create method with a converted StatusType. ### Method create ### Signature `default ResponseEntity<Problem> create(HttpStatus status, Throwable throwable, NativeWebRequest request, HttpHeaders headers)` ### Parameters - **status** (`org.springframework.http.HttpStatus`) - Required - Spring HTTP status enum - **throwable** (`Throwable`) - Required - Exception being caught - **request** (`NativeWebRequest`) - Required - Incoming request - **headers** (`HttpHeaders`) - Required - HTTP headers to include in the response ### Returns `ResponseEntity<Problem>` ### Notes Delegates to `create(toStatus(status), throwable, request, headers)`. ```