### HTTP Request/Response Examples for Spring Web Source: https://github.com/zalando/problem-spring-web/blob/main/README.md These examples showcase typical HTTP requests and their corresponding problem responses generated by a Spring Web application. The first example shows a GET request with an unsupported Accept header, resulting in a 406 Not Acceptable response. The second example demonstrates a POST request to an unsupported endpoint, leading to a 405 Method Not Allowed response. ```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" } ``` ```http POST /products/123 HTTP/1.1 Content-Type: application/json {} ``` ```http HTTP/1.1 405 Method Not Allowed Allow: GET Content-Type: application/problem+json { "title": "Method Not Allowed", "status": 405, "detail": "POST not supported" } ``` -------------------------------- ### Configure Stack Traces and Causal Chains (YAML) Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Example YAML configuration demonstrating how enabling both stack traces and causal chains results in a detailed problem response structure, including nested causes and stack trace information. ```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)" ] } } } ``` -------------------------------- ### API Usage Examples Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Illustrates how the Problem Spring Web library handles API requests and generates corresponding problem responses for common scenarios like unacceptable media types and unsupported methods. ```APIDOC ## Usage Assuming a controller with the following endpoints: ```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(); } } ``` ### Example 1: GET Request with Unacceptable Media Type **Request:** ```http GET /products/123 HTTP/1.1 Accept: application/xml ``` **Response:** ```http HTTP/1.1 406 Not Acceptable Content-Type: application/problem+json { "title": "Not Acceptable", "status": 406, "detail": "Could not find acceptable representation" } ``` ### Example 2: POST Request to an Unsupported Method **Request:** ```http POST /products/123 HTTP/1.1 Content-Type: application/json {} ``` **Response:** ```http HTTP/1.1 405 Method Not Allowed Allow: GET Content-Type: application/problem+json { "title": "Method Not Allowed", "status": 405, "detail": "POST not supported" } ``` ``` -------------------------------- ### Spring Web Controller Example Source: https://github.com/zalando/problem-spring-web/blob/main/README.md This Java code defines a Spring Web controller for managing products. It includes endpoints for retrieving a product by ID and updating a product. The example illustrates typical Spring MVC annotations for request mapping, HTTP methods, and content negotiation. ```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(); } } ``` -------------------------------- ### Customizing Problem Handling with AdviceTrait Source: https://github.com/zalando/problem-spring-web/blob/main/README.md This section details how to customize various aspects of the problem handling process provided by AdviceTrait, including creation, logging, content negotiation, fallback, and post-processing. It also provides an example of customizing MissingServletRequestParameterAdviceTrait. ```APIDOC ## Customization The problem handling process provided by `AdviceTrait` allows for customization of several aspects: | 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 | ### Example: Customizing MissingServletRequestParameterAdviceTrait This example demonstrates adding a `parameter` extension field to the `Problem` when customizing `MissingServletRequestParameterAdviceTrait`. ```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()); } } ``` ``` -------------------------------- ### 503 Service Unavailable Problem Response Example Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md An example of the HTTP response generated when a circuit breaker is open. It demonstrates the structure of a 503 Service Unavailable problem object, including title and status. ```http HTTP/1.1 503 Service Unavailable Content-Type: application/problem+json { "title": "Service Unavailable", "status": 503 } ``` -------------------------------- ### Spring Boot Application Configuration Source: https://context7.com/zalando/problem-spring-web/llms.txt Configure a Spring Boot application to exclude default error handling, allowing Problem Spring Web to manage error responses. This setup is essential for consistent error reporting in RESTful APIs. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; @SpringBootApplication(exclude = ErrorMvcAutoConfiguration.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### Extend Problem Responses with Custom Fields (Java) Source: https://context7.com/zalando/problem-spring-web/llms.txt Override the `prepare` method to add custom fields to Problem responses. This example demonstrates adding 'parameter' and 'expectedType' for missing request parameters. It requires the `zalando-problem-spring-web` dependency. ```java import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.Problem; import org.zalando.problem.ProblemBuilder; import org.zalando.problem.StatusType; import org.zalando.problem.spring.web.advice.routing.MissingServletRequestParameterAdviceTrait; import java.net.URI; @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()) .with("expectedType", exception.getParameterType()); } } ``` -------------------------------- ### Add WebExceptionHandler for Specific HTTP Statuses in Spring WebFlux Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md Provides an example of adding a specific WebExceptionHandler in Spring WebFlux. This is required for certain advice traits like ResponseStatusAdviceTrait, MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait, and UnsupportedMediaTypeAdviceTrait when the request handler is not invoked, ensuring proper error responses for 404, 405, 406, and 415 status codes. ```java import org.springframework.context.annotation.Bean; import org.springframework.web.server.WebExceptionHandler; // ... other imports @Bean public WebExceptionHandler specificExceptionHandler() { // Implementation details for handling specific exceptions // This is a placeholder and would typically involve custom logic return (exchange, ex) -> { // Handle the exception and return an appropriate response return exchange.getResponse().setComplete(); }; } ``` -------------------------------- ### Integrating OpenApiValidationAdviceTrait with ProblemHandling in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Demonstrates the integration of ProblemHandling and OpenApiValidationAdviceTrait. This allows for handling exceptions related to invalid requests or responses as defined by OpenAPI specifications. ```java import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice class ExceptionHandling implements ProblemHandling, OpenApiValidationAdviceTrait { } ``` -------------------------------- ### Add Spring Boot Starter Dependency Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md This XML snippet shows how to add the problem-spring-web starter module to your Maven dependencies for Spring Boot projects. This provides a default working configuration for handling problems. ```xml org.zalando problem-spring-web-starter ${problem-spring-web.version} ``` -------------------------------- ### Add Spring Web Starter Dependency (Maven) Source: https://context7.com/zalando/problem-spring-web/llms.txt Include the problem-spring-web-starter dependency in your Maven project to automatically configure problem handling in Spring Boot applications. ```xml org.zalando problem-spring-web-starter 0.29.1 ``` -------------------------------- ### Customize MissingServletRequestParameterAdviceTrait in Java Source: https://github.com/zalando/problem-spring-web/blob/main/README.md This Java code demonstrates how to customize the MissingServletRequestParameterAdviceTrait by implementing the prepare method. It adds a 'parameter' extension field to the Problem object, containing the name of the missing request parameter. This customization helps provide more specific error details to the client. ```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()); } } ``` -------------------------------- ### Basic Exception Handling with ProblemHandling in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Demonstrates the basic implementation of the ProblemHandling interface within a Spring @ControllerAdvice class. This serves as a foundation for custom exception handling strategies. ```java import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice class ExceptionHandling implements ProblemHandling { } ``` -------------------------------- ### Enable Stack Traces in ProblemModule (Java) Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Configures the ObjectMapper to register the ProblemModule with stack traces enabled. This allows for detailed debugging information to be included in problem responses. ```java ObjectMapper mapper = new ObjectMapper() .registerModule(new ProblemModule().withStackTraces()); ``` -------------------------------- ### Spring Security Integration for Problem Details Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md This section details the integration of Spring Security with Problem Details. It involves implementing `ProblemHandling` and `SecurityAdviceTrait` for custom exception handling during security-related events. A `SecurityConfiguration` bean is provided to configure the `authenticationEntryPoint` and `accessDeniedHandler` using `SecurityProblemSupport`. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, SecurityAdviceTrait { } ``` ```java @Configuration @Import(SecurityProblemSupport.class) public class SecurityConfiguration { @Autowired private SecurityProblemSupport problemSupport; @Bean public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) { return http.exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport) .and().build(); } } ``` ```java @ControllerAdvice public class SecurityExceptionHandler implements SecurityAdviceTrait { } ``` -------------------------------- ### Configuration for NoHandlerFoundAdviceTrait in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Shows the necessary Spring configuration properties to enable the NoHandlerFoundAdviceTrait. This configuration ensures that Spring MVC throws an exception when no handler is found for a request. ```yaml spring: resources: add-mappings: false mvc: throw-exception-if-no-handler-found: true ``` -------------------------------- ### Integrating SecurityAdviceTrait with ProblemHandling in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Combines the ProblemHandling and SecurityAdviceTrait interfaces in a Spring @ControllerAdvice class. This allows for centralized handling of both general problems and security-related exceptions. ```java import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice class ExceptionHandling implements ProblemHandling, SecurityAdviceTrait { } ``` -------------------------------- ### Configure Problem Handling for Spring WebFlux Source: https://context7.com/zalando/problem-spring-web/llms.txt Provides the necessary configuration to enable Problem handling for reactive Spring WebFlux applications. This involves defining a `ProblemExceptionHandler` bean with a high order of precedence and ensuring the `ProblemHandling` interface is implemented. ```java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.server.WebExceptionHandler; import org.zalando.problem.spring.webflux.advice.ProblemExceptionHandler; import org.zalando.problem.spring.webflux.advice.ProblemHandling; @ControllerAdvice class ExceptionHandling implements ProblemHandling { } @Configuration public class WebFluxConfiguration { @Bean @Order(-2) // Must have precedence over default handlers public WebExceptionHandler problemExceptionHandler( ObjectMapper mapper, ProblemHandling problemHandling) { return new ProblemExceptionHandler(mapper, problemHandling); } } ``` ```xml org.zalando problem-spring-webflux 0.29.1 ``` -------------------------------- ### Implementing SecurityExceptionHandler in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Provides a simple implementation of the SecurityAdviceTrait within a Spring @ControllerAdvice. This class is responsible for handling security-related exceptions and returning appropriate problem objects. ```java import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice public class SecurityExceptionHandler implements SecurityAdviceTrait { } ``` -------------------------------- ### Add Web MVC Dependencies Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md This XML snippet outlines the dependencies required for integrating problem-spring-web into a Spring Web MVC project without using the starter module. It includes the core library and the Jackson datatype for problem serialization. ```xml org.zalando problem-spring-web ${problem-spring-web.version} org.zalando jackson-datatype-problem 0.27.1 ``` -------------------------------- ### Integrating CircuitBreakerOpenAdviceTrait with ProblemHandling in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Shows how to combine ProblemHandling and CircuitBreakerOpenAdviceTrait for handling circuit breaker exceptions. This integration translates CircuitBreakerOpenException into a 503 Service Unavailable response. ```java import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice class ExceptionHandling implements ProblemHandling, CircuitBreakerOpenAdviceTrait { } ``` -------------------------------- ### Spring Boot Application Properties for Problem Handling Source: https://context7.com/zalando/problem-spring-web/llms.txt Configure Spring Boot properties to enable proper Problem handling, particularly for 404 Not Found responses. These settings ensure that missing handlers and resources are reported correctly. ```yaml # application.yml spring: mvc: throw-exception-if-no-handler-found: true web: resources: add-mappings: false ``` -------------------------------- ### Register Problem Modules with ObjectMapper in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md This snippet demonstrates how to register the `ProblemModule` and `ConstraintViolationProblemModule` with your ObjectMapper. This is crucial if you are not using the starter module to ensure proper serialization and deserialization of problem details. ```java import org.zalando.problem.spring.web.advice.ProblemModule; import org.zalando.problem.spring.web.advice.ConstraintViolationProblemModule; import org.springframework.context.annotation.Bean; // ... other imports public class AppConfig { @Bean public ProblemModule problemModule() { return new ProblemModule(); } @Bean public ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } } ``` -------------------------------- ### Implement ProblemHandling in Spring WebFlux ControllerAdvice Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md Demonstrates how to implement the ProblemHandling interface in a Spring WebFlux ControllerAdvice. This allows for centralized exception handling and consistent problem reporting across the application. ```java import org.zalando.problem.spring.webflux.advice.ProblemHandling; import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice class ExceptionHandling implements ProblemHandling { } ``` -------------------------------- ### Spring Security Configuration for Problem Handling in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Configures Spring Security to use SecurityProblemSupport for handling authentication and access denied exceptions. This ensures that problems are returned in a standardized format. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.ResourceServerConfigurerAdapter; @Configuration @Import(SecurityProblemSupport.class) public class SecurityConfiguration extends ResourceServerConfigurerAdapter { @Autowired private SecurityProblemSupport problemSupport; @Override public void configure(final HttpSecurity http) { http.exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport); } } ``` -------------------------------- ### Customize Exception Logging in Spring Web Source: https://context7.com/zalando/problem-spring-web/llms.txt Illustrates how to override the default logging behavior for exceptions handled by the Problem library. By implementing the `log` method in a `ProblemHandling` advice, you can customize logging based on HTTP status codes and problem details. ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.NativeWebRequest; import org.zalando.problem.Problem; import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice public class ExceptionHandling implements ProblemHandling { private static final Logger LOG = LoggerFactory.getLogger(ExceptionHandling.class); @Override public void log(Throwable throwable, Problem problem, NativeWebRequest request, HttpStatus status) { if (status.is5xxServerError()) { LOG.error("Internal error [{}]: {}", problem.getStatus(), problem.getDetail(), throwable); } else if (status.is4xxClientError()) { LOG.warn("Client error [{}]: {}", problem.getStatus(), problem.getDetail()); } else { LOG.debug("Problem [{}]: {}", problem.getStatus(), problem.getDetail()); } } } ``` -------------------------------- ### Selective Trait Implementation in Java Source: https://context7.com/zalando/problem-spring-web/llms.txt Implement individual advice traits for fine-grained control over exception handling in Spring Web applications. This approach allows specific exceptions to be handled while others fall through to default Spring mechanisms. ```java import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.general.ThrowableAdviceTrait; import org.zalando.problem.spring.web.advice.http.MethodNotAllowedAdviceTrait; import org.zalando.problem.spring.web.advice.http.NotAcceptableAdviceTrait; import org.zalando.problem.spring.web.advice.validation.ConstraintViolationAdviceTrait; import org.zalando.problem.spring.web.advice.validation.MethodArgumentNotValidAdviceTrait; @ControllerAdvice public class SelectiveExceptionHandling implements ThrowableAdviceTrait, MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait, ConstraintViolationAdviceTrait, MethodArgumentNotValidAdviceTrait { // Only these specific exception types will be handled // Other exceptions fall through to default Spring handling } ``` -------------------------------- ### Integrate Circuit Breaker Exception Handling in Spring Web Source: https://context7.com/zalando/problem-spring-web/llms.txt Shows how to integrate Failsafe circuit breaker exceptions into Spring Web's error handling. This allows returning a 503 Service Unavailable response with `Retry-After` information when the circuit breaker is open, leveraging `CircuitBreakerOpenAdviceTrait`. ```java import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.network.CircuitBreakerOpenAdviceTrait; @ControllerAdvice class ExceptionHandling implements ProblemHandling, CircuitBreakerOpenAdviceTrait { } ``` -------------------------------- ### Integrate Problem with Spring Security (Java) Source: https://context7.com/zalando/problem-spring-web/llms.txt Integrate Problem responses with Spring Security for handling authentication and authorization failures. This involves implementing `SecurityAdviceTrait` in an exception handler and configuring `SecurityProblemSupport` within the Spring Security filter chain. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport; // Exception handler with security support @ControllerAdvice class ExceptionHandling implements ProblemHandling, SecurityAdviceTrait { } // Security configuration @Configuration @Import(SecurityProblemSupport.class) public class SecurityConfiguration { @Autowired private SecurityProblemSupport problemSupport; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .exceptionHandling(handling -> handling .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport)) .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated()) .build(); } } ``` -------------------------------- ### Failsafe Integration for CircuitBreakerOpenException Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md This integration adds support for `CircuitBreakerOpenException` by translating an open circuit breaker into a `503 Service Unavailable` response. It requires implementing `ProblemHandling` and `CircuitBreakerOpenAdviceTrait`. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, CircuitBreakerOpenAdviceTrait { } ``` ```http HTTP/1.1 503 Service Unavailable Content-Type: application/problem+json { "title": "Service Unavailable", "status": 503 } ``` -------------------------------- ### Enable Causal Chains in Exception Handling (Java) Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Overrides the default behavior to enable causal chains for problem exceptions. This provides a more comprehensive view of the exception hierarchy. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling { @Override public boolean isCausalChainsEnabled() { return true; } } ``` -------------------------------- ### Restrict ControllerAdvice Scope (Java) Source: https://github.com/zalando/problem-spring-web/blob/main/README.md Demonstrates how to restrict the scope of a @ControllerAdvice to specific controller types using the assignableTypes attribute. This can lead to certain exceptions not being handled. ```java @ControllerAdvice(assignableTypes = ExampleController.class) public final class ExceptionHandling implements ProblemHandling ``` -------------------------------- ### Configure Jackson ObjectMapper for Problem Serialization (Java) Source: https://context7.com/zalando/problem-spring-web/llms.txt Register ProblemModule and ConstraintViolationProblemModule with your ObjectMapper for proper Problem serialization when not using the starter module. This configuration is essential for correctly handling problem details in JSON responses. ```java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.zalando.problem.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { @Bean public ProblemModule problemModule() { return new ProblemModule(); } @Bean public ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } // To enable stack traces in responses (not recommended for production) @Bean public ObjectMapper objectMapper() { return new ObjectMapper() .registerModule(new ProblemModule().withStackTraces()); } } ``` -------------------------------- ### Handle Bean Validation Exceptions in Spring Web Source: https://context7.com/zalando/problem-spring-web/llms.txt Demonstrates how to configure Spring Web to catch JSR-380 constraint violations and return detailed field-level error information using the Problem library. This requires the `jakarta.validation` API and Spring Web integration. ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.zalando.problem.Problem; import org.zalando.problem.spring.web.advice.ProblemHandling; import jakarta.validation.Valid; import jakarta.validation.constraints.*; // Controller with validation @RestController @RequestMapping("/users") public class UserController { @PostMapping public User createUser(@Valid @RequestBody CreateUserRequest request) { // Implementation return new User(request.email(), request.name()); } } // Request DTO with validation record CreateUserRequest( @NotNull @Email String email, @NotBlank @Size(min = 2, max = 100) String name, @Min(18) @Max(150) Integer age ) {} // Exception handler @ControllerAdvice class ExceptionHandling implements ProblemHandling { } ``` -------------------------------- ### Add Spring Web and Jackson Datatype Problem Dependencies (Maven) Source: https://context7.com/zalando/problem-spring-web/llms.txt For non-Spring Boot applications or manual configuration, add the problem-spring-web and jackson-datatype-problem dependencies to your Maven project. ```xml org.zalando problem-spring-web 0.29.1 org.zalando jackson-datatype-problem 0.27.1 ``` -------------------------------- ### Excluding ErrorMvcAutoConfiguration in Spring Boot Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-web/README.md Illustrates how to exclude Spring Boot's ErrorMvcAutoConfiguration when using custom exception handling. This prevents conflicts and ensures the custom advice traits are applied correctly. ```java import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; @EnableAutoConfiguration(exclude = ErrorMvcAutoConfiguration.class) class CustomExceptionHandling { } ``` -------------------------------- ### Add Problem Spring WebFlux Dependencies (Maven) Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md Include these dependencies in your Maven project to enable Problem integration with Spring WebFlux. The first dependency is for the core WebFlux integration, and the second is for Jackson's support of the Problem object. ```xml org.zalando problem-spring-webflux ${problem-spring-webflux.version} org.zalando jackson-datatype-problem 0.27.1 ``` -------------------------------- ### Register Problem Modules with ObjectMapper in Java Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md Registers the ProblemModule and ConstraintViolationProblemModule with Spring's ObjectMapper. These modules are essential for serializing and deserializing Problem objects, ensuring proper handling of exceptions and validation errors in a Spring WebFlux application. ```java import org.zalando.problem.spring.web.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; import org.springframework.context.annotation.Bean; // ... other imports @Bean public ProblemModule problemModule() { return new ProblemModule(); } @Bean public ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } ``` -------------------------------- ### Configure Problem Exception Handler for Spring WebFlux Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md This code configures a `ProblemExceptionHandler` bean for Spring WebFlux. It ensures that this handler has precedence over other default exception handlers. It requires an `ObjectMapper` and a `ProblemHandling` instance. ```java @Order(-2) // The handler must have precedence over WebFluxResponseStatusExceptionHandler and Spring Boot's ErrorWebExceptionHandler public WebExceptionHandler problemExceptionHandler(ObjectMapper mapper, ProblemHandling problemHandling) { return new ProblemExceptionHandler(mapper, problemHandling); } ``` -------------------------------- ### Implement ProblemHandling Interface (Java) Source: https://context7.com/zalando/problem-spring-web/llms.txt Implement the ProblemHandling interface in a Spring @ControllerAdvice class to enable comprehensive exception handling for your Spring application. This provides handlers for various common exceptions out-of-the-box. ```java import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice public class ExceptionHandling implements ProblemHandling { // All built-in exception handlers are automatically available // No additional code needed for basic setup } ``` -------------------------------- ### OpenAPI Request Validator Integration Source: https://github.com/zalando/problem-spring-web/blob/main/problem-spring-webflux/README.md This optional integration provides support for exceptions arising from invalid requests or responses as defined by OpenAPI specifications. It involves implementing `ProblemHandling` and `OpenApiValidationAdviceTrait`. ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling, OpenApiValidationAdviceTrait { } ``` -------------------------------- ### OpenAPI Validation Integration in Java Source: https://context7.com/zalando/problem-spring-web/llms.txt Integrate OpenAPI request validation exceptions from Atlassian's Swagger Request Validator into your Spring Web application. This ensures that requests conforming to your OpenAPI specification are validated. ```java import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.validation.OpenApiValidationAdviceTrait; @ControllerAdvice class ExceptionHandling implements ProblemHandling, OpenApiValidationAdviceTrait { } ``` -------------------------------- ### Enable Causal Chains for Nested Exceptions (Java) Source: https://context7.com/zalando/problem-spring-web/llms.txt Enable causal chain reporting to include nested exception information in Problem responses. This is achieved by implementing the `ProblemHandling` interface and returning `true` from `isCausalChainsEnabled()`. This aids in debugging by providing a clear view of the exception hierarchy. ```java import org.springframework.web.bind.annotation.ControllerAdvice; import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice public class ExceptionHandling implements ProblemHandling { @Override public boolean isCausalChainsEnabled() { return true; // Enable nested cause information } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.