### Security Configuration with UnauthorizedEntryPoint Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example configuration for setting up an UnauthorizedEntryPoint in Spring Security. ```java http.httpBasic(AbstractHttpConfigurer::disable); http.authorizeHttpRequests(customizer -> customizer.anyRequest().authenticated()); http.exceptionHandling(customizer -> customizer.authenticationEntryPoint(unauthorizedEntryPoint));//<.> return http.build(); } } ``` -------------------------------- ### Custom Exception Example Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a custom RuntimeException for handling specific error scenarios like User Not Found. ```java package com.company.application.user; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(UserId userId) { super("Could not find user with id " + userId); } } ``` -------------------------------- ### messages.properties Example Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example entry in the messages.properties file for translating error messages. ```properties UserAlreadyExists=The user already exists ``` -------------------------------- ### Example Java class for ApplicationException Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc A Java class representing a custom application exception. ```java public class ApplicationException extends RuntimeException {} ``` -------------------------------- ### Security Configuration with AccessDeniedHandler Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example configuration for setting up an AccessDeniedHandler in Spring Security. ```java import tools.jackson.databind.ObjectMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.UnauthorizedEntryPoint; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorCodeMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorMessageMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.HttpStatusMapper; import org.springframework.context.annotation.Bean; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; public class WebSecurityConfiguration { @Bean public AccessDeniedHandler accessDeniedHandler(HttpStatusMapper httpStatusMapper, ErrorCodeMapper errorCodeMapper, ErrorMessageMapper errorMessageMapper, ObjectMapper objectMapper) { //<.> return new ApiErrorResponseAccessDeniedHandler(objectMapper, httpStatusMapper, errorCodeMapper, errorMessageMapper); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, AccessDeniedHandler accessDeniedHandler) throws Exception { http.httpBasic(AbstractHttpConfigurer::disable); http.authorizeHttpRequests(customizer -> customizer.anyRequest().authenticated()); http.exceptionHandling(customizer -> customizer.accessDeniedHandler(accessDeniedHandler));//<.> return http.build(); } } ``` -------------------------------- ### JSON Response Example Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response generated by a custom exception handler. ```json { "code": "MY_CUSTOM_EXCEPTION", "message": "parent exception message", "cause": { "code": "CAUSE", "message": "child IOException message" } } ``` -------------------------------- ### Example Java class extending RuntimeException Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc A sample custom exception class that extends RuntimeException. ```java public class MyException extends RuntimeException {} ``` -------------------------------- ### Example Custom Exception Handler Implementation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc An example implementation of a custom exception handler to add the first-level cause of an Exception. ```java The implementation could look something like this: ``` -------------------------------- ### Unauthorized EntryPoint Bean Configuration Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example Java configuration for defining an UnauthorizedEntryPoint bean. ```java import tools.jackson.databind.ObjectMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.UnauthorizedEntryPoint; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorCodeMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.ErrorMessageMapper; import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.HttpStatusMapper; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; public class WebSecurityConfiguration { @Bean public UnauthorizedEntryPoint unauthorizedEntryPoint(HttpStatusMapper httpStatusMapper, ErrorCodeMapper errorCodeMapper, ErrorMessageMapper errorMessageMapper, ObjectMapper objectMapper) { //<.> return new UnauthorizedEntryPoint(httpStatusMapper, errorCodeMapper, errorMessageMapper, objectMapper); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, UnauthorizedEntryPoint unauthorizedEntryPoint) throws Exception { ``` -------------------------------- ### Problem Detail response with type prefix Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a Problem Detail response with a configured type prefix. ```json { "type": "https://api.example.com/errors/user-not-found", "title": "Not Found", "status": 404, "detail": "Could not find user with id 123" } ``` -------------------------------- ### Problem Detail response format Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of the RFC 9457 Problem Detail response format when enabled. ```json { "type": "user-not-found", "title": "Not Found", "status": 404, "detail": "Could not find user with id 123" } ``` -------------------------------- ### Configure settings for RuntimeException subclasses Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of setting HTTP status, error code, and message for all RuntimeException subclasses. ```properties error.handling.http-statuses.java.lang.RuntimeException=bad_request error.handling.codes.java.lang.RuntimeException=RUNTIME_EXCEPTION error.handling.messages.java.lang.RuntimeException=A runtime exception has happened ``` -------------------------------- ### Combined Security Configuration Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of combining both UnauthorizedEntryPoint and AccessDeniedHandler in Spring Security. ```java @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, UnauthorizedEntryPoint unauthorizedEntryPoint, AccessDeniedHandler accessDeniedHandler) throws Exception { http.httpBasic().disable(); http.authorizeHttpRequests().anyRequest().authenticated(); http.exceptionHandling() .authenticationEntryPoint(unauthorizedEntryPoint) .accessDeniedHandler(accessDeniedHandler); return http.build(); } ``` -------------------------------- ### Example Request Body for Validation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Java class demonstrating validation annotations for request body fields. ```java public class ExampleRequestBody { @Size(min = 10) private String name; @NotBlank private String favoriteMovie; // getters and setters } ``` -------------------------------- ### General override for Exception Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of configuring a global error message for a specific exception type. ```properties error.handling.messages.com.company.application.user.UserNotFoundException=The user was not found ``` -------------------------------- ### Custom Exception Handlers with @WebFluxTest Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of importing custom exception handlers for @WebFluxTest. ```java @WebFluxTest(MyController.class) @Import(MyCustomExceptionHandler.class) class MyControllerTests { } ``` -------------------------------- ### Custom Exception Handler Example Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a custom exception handler implementing ApiExceptionHandler to create a custom JSON response. ```java include::{include-test}/handler/CustomExceptionApiExceptionHandler.java[] ``` -------------------------------- ### Custom Exception Handlers with @WebMvcTest Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of importing custom exception handlers for @WebMvcTest. ```java @WebMvcTest(MyController.class) @Import(MyCustomExceptionHandler.class) class MyControllerTests { } ``` -------------------------------- ### Problem Detail response with disabled kebab-case conversion Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a Problem Detail response when kebab-case conversion is disabled. ```json { "type": "USER_NOT_FOUND", "title": "Not Found", "status": 404, "detail": "Could not find user with id 123" } ``` -------------------------------- ### Custom Logging Service Filter Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example implementation of a custom LoggingServiceFilter to conditionally log exceptions. ```java import io.github.wimdeblauwe.errorhandlingspringbootstarter.LoggingServiceFilter; import org.springframework.stereotype.Component; @Component public class MyLoggingServiceFilter implements LoggingServiceFilter { @Override public boolean shouldLogException(ApiErrorResponse errorResponse, Throwable exception) { if( exception instanceof SomeException ) { return false; } return true; } } ``` -------------------------------- ### Example Validation Failed JSON Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc A typical JSON response structure when validation fails. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='exampleRequestBody'. Error count: 4", "fieldErrors": [ { "code": "INVALID_SIZE", "property": "name", "message": "size must be between 10 and 2147483647", "rejectedValue": "", "path": "name" }, { "code": "REQUIRED_NOT_BLANK", "property": "favoriteMovie", "message": "must not be blank", "rejectedValue": null, "path": "favoriteMovie" } ], "globalErrors": [ { "code": "ValidCustomer", "message": "Invalid customer" }, { "code": "ValidCustomer", "message": "UserAlreadyExists" } ], "parameterErrors": [ { "code": "REQUIRED_NOT_NULL", "message": "must not be null", "parameter": "extraArg", "rejectedValue": null } ] } ``` -------------------------------- ### Default Exception Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response for a UserNotFoundException when thrown from a @RestController method. ```json { "code": "USER_NOT_FOUND", "message": "Could not find user with id 123" } ``` -------------------------------- ### Custom Validation Annotation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a custom validation annotation used for defining validation rules. ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = CustomerValidator.class) public @interface ValidCustomer { String message() default "Invalid customer"; Class[] groups() default {}; Class[] payload() default {}; } ``` -------------------------------- ### JSON Response with FULL_QUALIFIED_NAME Strategy Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response when using the FULL_QUALIFIED_NAME default error code strategy for UserNotFoundException. ```json { "code": "com.company.application.user.UserNotFoundException", "message": "Could not find user with id 123" } ``` -------------------------------- ### Validation errors with Problem Detail Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a Problem Detail response for validation errors, including 'fieldErrors'. ```json { "type": "validation-failed", "title": "Bad Request", "status": 400, "detail": "Validation failed for object='exampleRequestBody'. Error count: 2", "fieldErrors": [ { "code": "INVALID_SIZE", "property": "name", "message": "size must be between 10 and 2147483647", "rejectedValue": "", "path": "name" }, { "code": "REQUIRED_NOT_BLANK", "property": "favoriteMovie", "message": "must not be blank", "rejectedValue": null, "path": "favoriteMovie" } ] } ``` -------------------------------- ### Custom properties with Problem Detail Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a Problem Detail response including custom properties added via @ResponseErrorProperty. ```json { "type": "https://api.example.com/errors/optimistic-locking-error", "title": "Conflict", "status": 409, "detail": "Object of class [com.example.user.User] with identifier [1]: optimistic locking failed", "identifier": "1", "persistentClassName": "com.example.user.User" } ``` -------------------------------- ### Controller with Validated Request Body Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example Spring Boot controller demonstrating the use of @Valid and @RequestBody for validation. ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.validation.Valid; @RestController @RequestMapping("/example") public class MyExampleController { @PostMapping public MyResponse doSomething(@Valid @RequestBody ExampleRequestBody requestBody ) { // ... } } ``` -------------------------------- ### General override for Validation Annotation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of configuring a global error message for a specific validation annotation. ```properties error.handling.messages.NotBlank=The property should not be blank ``` -------------------------------- ### Set HTTP response status via properties Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of setting HTTP response status for a specific exception type using application properties. ```properties error.handling.http-statuses.java.lang.IllegalArgumentException=bad_request ``` -------------------------------- ### Custom HttpResponseStatusFromExceptionMapper implementation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example implementation of HttpResponseStatusFromExceptionMapper to extract response status from custom exception types. ```java import io.github.wimdeblauwe.errorhandlingspringbootstarter.mapper.HttpResponseStatusFromExceptionMapper; import org.springframework.http.HttpStatusCode; import org.springframework.stereotype.Component; @Component class CustomHttpResponseStatusFromExceptionMapper implements HttpResponseStatusFromExceptionMapper { @Override public boolean canExtractResponseStatus(Throwable exception) { return exception instanceof MyCustomHttpResponseStatusException; } @Override public HttpStatusCode getResponseStatus(Throwable exception) { return ((MyCustomHttpResponseStatusException) exception).getHttpStatusCode(); } } ``` -------------------------------- ### JSON Response with General Error Code Override Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response after overriding the error code for IllegalArgumentException. ```json { "code": "ILLEGAL_ARGUMENT", "message": "argument was not as expected" } ``` -------------------------------- ### Global Error Response Customization with ApiErrorResponseCustomizer Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of implementing ApiErrorResponseCustomizer to globally add properties like a timestamp to all error responses. ```java @Bean public ApiErrorResponseCustomizer timestampErrorResponseCustomizer() { return new ApiErrorResponseCustomizer() { @Override public void customize(ApiErrorResponse response) { response.addErrorProperty("instant", Instant.now()); } }; } ``` -------------------------------- ### UserNotFoundException with @ResponseErrorProperty Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a custom exception class annotated with @ResponseErrorProperty to include the userId in the JSON response. ```java import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseErrorCode; import org.springframework.web.bind.annotation.ResponseErrorProperty; @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseErrorCode("USER_NOT_FOUND") public class UserNotFoundException extends RuntimeException { @ResponseErrorProperty // <.> private final UserId userId; public UserNotFoundException(UserId userId) { super(String.format("Could not find user with id %s", userId)); this.userId = userId; } } ``` -------------------------------- ### Set HTTP response status via @ResponseStatus Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of setting a specific HTTP response status using @ResponseStatus on a custom exception class. ```java package com.company.application.user; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) //<.> public class UserNotFoundException extends RuntimeException { public UserNotFoundException(UserId userId) { super("Could not find user with id " + userId); } } ``` -------------------------------- ### Java Class with @Pattern Annotation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example Java class CreateUserRequestBody with a password field annotated with @Pattern for validation. ```java public class CreateUserRequestBody { @Pattern(".*{8}") private String password; // getters and setters } ``` -------------------------------- ### Validation Failed Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response when validation fails for a request body, including field errors. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='exampleRequestBody'. Error count: 2", "fieldErrors": [ { "code": "INVALID_SIZE", "property": "name", "message": "size must be between 10 and 2147483647", "rejectedValue": "", "path": "name" }, { "code": "REQUIRED_NOT_BLANK", "property": "favoriteMovie", "message": "must not be blank", "rejectedValue": null, "path": "favoriteMovie" } ] } ``` -------------------------------- ### Annotating Endpoints for Error Responses Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of how to use the @ApiResponse annotation to document error responses in Swagger for a Spring Boot controller. ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; // Assuming ApiErrorResponse.class is defined elsewhere // class ApiErrorResponse { ... } public class ExampleController { @GetMapping("/{id}") @ApiResponse( responseCode = "404", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ApiErrorResponse.class) ) ) public ResponseEntity getExample(@PathVariable String id) { // Your controller logic here return ResponseEntity.ok("Example response"); } } ``` -------------------------------- ### Field specific override for Validation Annotation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of configuring an error message for a specific field and validation annotation combination. ```properties error.handling.messages.password.Pattern=The password complexity rules are not met. A password must be 8 characters minimum. ``` -------------------------------- ### JSON Response with Default Error Message Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response showing the default behavior where the exception message is mapped to the 'message' field. ```json { "code": "USER_NOT_FOUND", "message": "Could not find user with id 123" // <.> } ``` -------------------------------- ### JSON Response with Per Class Error Code Override Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response when using the @ResponseErrorCode annotation on UserNotFoundException. ```json { "code": "COULD_NOT_FIND_USER", "message": "Could not find user with id 123" } ``` -------------------------------- ### Java Class with @ResponseErrorCode Annotation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example Java class UserNotFoundException annotated with @ResponseErrorCode to define a custom error code. ```java package com.company.application.user; import io.github.wimdeblauwe.errorhandlingspringbootstarter.ResponseErrorCode; @ResponseErrorCode("COULD_NOT_FIND_USER") public class UserNotFoundException extends RuntimeException { public UserNotFoundException(UserId userId) { super("Could not find user with id " + userId); } } ``` -------------------------------- ### JSON Response with General Validation Error Code Override Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response after overriding the error code for @Size validation. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='exampleRequestBody'. Error count: 1", "fieldErrors": [ { "code": "SIZE_REQUIREMENT_NOT_MET", "property": "name", "message": "size must be between 10 and 2147483647", "rejectedValue": "", "path": "name" } ] } ``` -------------------------------- ### Custom Exception with @ResponseErrorProperty Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of a custom exception class annotated with @ResponseErrorProperty to include extra properties in the JSON response. ```java @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseErrorCode("USER_NOT_FOUND") public class UserNotFoundException extends RuntimeException { private final UserId userId; public UserNotFoundException(UserId userId) { super(String.format("Could not find user with id %s", userId)); this.userId = userId; } @ResponseErrorProperty // <.> public String getUserId() { ``` -------------------------------- ### Customizing Default Error Messages Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example of how to customize default error messages by providing specific properties. An empty value for an exception class resets to default messaging behavior. ```properties error.handling.messages.java.lang.RuntimeException=A runtime exception has happened error.handling.search-super-class-hierarchy=true error.handling.messages.my.ApplicationException= ``` -------------------------------- ### JSON Response with Default @Pattern Validation Error Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response showing the default error code for a @Pattern validation failure. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='createUserRequestBody'. Error count: 1", "fieldErrors": [ { "code": "REGEX_PATTERN_VALIDATION_FAILED", "property": "password", "message": "must match \".*{8}\"", "rejectedValue": "", "path": "password" } ] } ``` -------------------------------- ### JSON Response with Field Specific Validation Error Override Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON response showing the custom error code for a @Pattern validation on a 'password' field. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='createUserRequestBody'. Error count: 1", "fieldErrors": [ { "code": "PASSWORD_COMPLEXITY_REQUIREMENTS_NOT_MET", "property": "password", "message": "must match \".*{8}\"", "rejectedValue": "", "path": "password" } ] } ``` -------------------------------- ### Invalid JSON Request Body Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Example JSON request body that would fail validation due to missing required fields and incorrect size. ```json { "name": "", "favoriteMovie": null } ``` -------------------------------- ### Configuring Problem Detail type prefix Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Properties to enable Problem Detail format and add a prefix to the 'type' field for fully qualified URIs. ```properties error.handling.use-problem-detail-format=true error.handling.problem-detail-type-prefix=https://api.example.com/errors/ ``` -------------------------------- ### Enabling Problem Detail format Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Property to enable the RFC 9457 Problem Detail format. ```properties error.handling.use-problem-detail-format=true ``` -------------------------------- ### Tag the commit Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/README.adoc Command to tag the current commit with a version number. ```bash git tag ``` -------------------------------- ### Update pom.xml with new version Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/README.adoc Command to update the pom.xml file with a new version number. ```bash mvn versions:set -DgenerateBackupPoms=false -DnewVersion= ``` -------------------------------- ### Exception Logging Configuration Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration properties to control exception logging behavior, including message only, full stack traces for specific classes, and full stack traces for HTTP status codes. ```properties error.handling.exception-logging=MESSAGE_ONLY error.handling.full-stacktrace-classes[0]=java.lang.NullPointerException error.handling.full-stacktrace-classes[1]=org.springframework.http.converter.HttpMessageNotReadableException ``` ```properties error.handling.full-stacktrace-http-statuses[0]=5xx error.handling.full-stacktrace-http-statuses[1]=403 ``` -------------------------------- ### Enable Super Class Hierarchy Search Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration to enable searching for error settings in superclasses of exceptions. ```properties error.handling.search-super-class-hierarchy=true ``` -------------------------------- ### Using messages.properties for Error Messages Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Demonstrates how to use the messages.properties file for internationalized error messages. ```java context.buildConstraintViolationWithTemplate("{UserAlreadyExists}").addConstraintViolation(); ``` -------------------------------- ### Custom Logging Level Configuration Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration properties to set specific log levels for different HTTP status codes. ```properties error.handling.log-levels.400=DEBUG error.handling.log-levels.401=INFO error.handling.log-levels.5xx=ERROR ``` -------------------------------- ### Gradle Dependency Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Dependency declaration for Gradle to include the error-handling-spring-boot-starter library. ```gradle compile 'io.github.wimdeblauwe:error-handling-spring-boot-starter:LATEST_VERSION_HERE' ``` -------------------------------- ### Maven Dependency Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Dependency declaration for Maven to include the error-handling-spring-boot-starter library. ```xml io.github.wimdeblauwe error-handling-spring-boot-starter LATEST_VERSION_HERE ``` -------------------------------- ### Response for RuntimeException subclass Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The resulting JSON response when a custom RuntimeException subclass is thrown and superclass hierarchy search is enabled. ```json { "code": "RUNTIME_EXCEPTION", "message": "A runtime exception has happened" } ``` -------------------------------- ### General override for Exception - Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The resulting JSON response when the UserNotFoundException is thrown and overridden. ```json { "code": "USER_NOT_FOUND", "message": "The user was not found" //<.> } ``` -------------------------------- ### Default response for Pattern validation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The default JSON response when a Pattern validation fails without specific overrides. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='createUserRequestBody'. Error count: 1", "fieldErrors": [ { "code": "REGEX_PATTERN_VALIDATION_FAILED", "property": "password", "message": "must match \".*{8}\", "rejectedValue": "", "path": "password" } ] } ``` -------------------------------- ### Disabling kebab-case conversion for Problem Detail type Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Properties to enable Problem Detail format and disable the conversion of error codes to kebab-case for the 'type' field. ```properties error.handling.use-problem-detail-format=true error.handling.problem-detail-convert-to-kebab-case=false ``` -------------------------------- ### Null Handling with includeIfNull Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Shows how to include a property in the JSON response even if its value is null, by setting includeIfNull=true on @ResponseErrorProperty. ```java @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseErrorCode("USER_NOT_FOUND") public class UserNotFoundException extends RuntimeException { private final UserId userId; public UserNotFoundException(UserId userId) { super(String.format("Could not find user with id %s", userId)); this.userId = userId; } @ResponseErrorProperty(includeIfNull=true) // <.> public String getUserId() { return userId.asString(); } } ``` -------------------------------- ### Properties for Default Error Code Strategy Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration property to set the default error code strategy to FULL_QUALIFIED_NAME. ```properties error.handling.default-error-code-strategy=FULL_QUALIFIED_NAME ``` -------------------------------- ### Custom Validator Implementation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Implementation of a custom validator for the ValidCustomer annotation. ```java public class CustomerValidator implements ConstraintValidator { @Override public boolean isValid(CreateCustomerFormData formData, ConstraintValidatorContext context) { if(...) { context.buildConstraintViolationWithTemplate("UserAlreadyExists").addConstraintViolation(); } } } ``` -------------------------------- ### Fallback Exception Handler Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Custom ControllerAdvice to handle exceptions from non-RestController classes. ```java import io.github.wimdeblauwe.errorhandlingspringbootstarter.servlet.ErrorHandlingControllerAdvice; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.web.bind.annotation.ControllerAdvice; import java.util.List; @ControllerAdvice @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) public class FallbackExceptionHandler extends ErrorHandlingControllerAdvice { public FallbackExceptionHandler(List handlers, FallbackApiExceptionHandler fallbackHandler, LoggingService loggingService) { super(handlers, fallbackHandler, loggingService); } } ``` -------------------------------- ### Custom Exception Handler Interface Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The ApiExceptionHandler interface that needs to be implemented for custom exception handling. ```java include::{include}/ApiExceptionHandler.java[] ``` -------------------------------- ### Customizing JSON Field Names Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration properties to customize the field names for 'code', 'message', 'fieldErrors', and 'globalErrors' in the JSON error response. ```properties error.handling.json-field-names.code=errorCode error.handling.json-field-names.message=description error.handling.json-field-names.field-errors=fieldFailures error.handling.json-field-names.global-errors=classFailures ``` -------------------------------- ### General override for Validation Annotation - Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The resulting JSON response when a NotBlank validation fails and is overridden. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='exampleRequestBody'. Error count: 1", "fieldErrors": [ { "code": "REQUIRED_NOT_BLANK", "property": "name", "message": "The property should not be blank",//<.> "rejectedValue": "", "path": "name" } ] } ``` -------------------------------- ### Field specific override for Validation Annotation - Response Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc The resulting JSON response when a Pattern validation on the 'password' field fails and is overridden. ```json { "code": "VALIDATION_FAILED", "message": "Validation failed for object='createUserRequestBody'. Error count: 1", "fieldErrors": [ { "code": "REGEX_PATTERN_VALIDATION_FAILED", "property": "password", "message": "The password complexity rules are not met. A password must be 8 characters minimum.", //<> "rejectedValue": "", "path": "password" } ] } ``` -------------------------------- ### Properties for General Override of Error Codes Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration property to override the error code for a specific exception class like IllegalArgumentException. ```properties error.handling.codes.java.lang.IllegalArgumentException=ILLEGAL_ARGUMENT ``` -------------------------------- ### Properties for General Override of Validation Error Codes Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration property to override the default error code for a Jakarta validation constraint like @Size. ```properties error.handling.codes.Size=SIZE_REQUIREMENT_NOT_MET ``` -------------------------------- ### Properties for Field Specific Override of Validation Error Codes Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Configuration property to override the error code for a @Pattern validation specifically for fields named 'password'. ```properties error.handling.codes.password.Pattern=PASSWORD_COMPLEXITY_REQUIREMENTS_NOT_MET ``` -------------------------------- ### Overriding Response Property Name Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Demonstrates how to override the default JSON property name for an error property using the 'value' argument of @ResponseErrorProperty. ```java @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseErrorCode("USER_NOT_FOUND") public class UserNotFoundException extends RuntimeException { ... @ResponseErrorProperty("id") public String getUserId() { return userId.asString(); } } ``` -------------------------------- ### Validation Error Case 2: @RequestParam with Validation Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Controller method with a @RequestParam parameter annotated with validation annotations and the controller class annotated with @Validated. ```java import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.validation.Valid; @RestController @RequestMapping("/example") @Validated public class MyExampleController { @GetMapping public MyResponse doSomething(@NotBlank @RequestParam("param") String param ) { // ... } } ``` -------------------------------- ### Validation Error Case 3: @Valid Request Parameters Class Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Controller method with a class parameter annotated with @Valid, where the class maps to request parameters. ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.validation.Valid; @RestController @RequestMapping("/example") public class MyExampleController { @GetMapping public MyResponse doSomething(@Valid ExampleRequestParameters requestParameters ) { // ... } } ``` -------------------------------- ### Validation Error Case 4: @Validated Spring Component Source: https://github.com/wimdeblauwe/error-handling-spring-boot-starter/blob/develop/src/docs/asciidoc/index.adoc Spring component annotated with @Validated, with parameters annotated with validation annotations. ```java import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; @Service @Validated public static class TestService { void doSomething(@Valid TestRequestBody requestBody, @NotNull String extraArg) { } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.