java / expert
Snippet
Functional Error Translation with Spring ProblemDetail Framework
Spring 6 introduced native RFC 7807 `ProblemDetail` support for standardized HTTP error responses. Utilizing `@RestControllerAdvice` along with dynamic metadata injection allows centralized exception translation and consistent API error contracts across all REST endpoints.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
@RestControllerAdvicepublic class GlobalProblemDetailsAdvice {@ExceptionHandler(DomainValidationException.class)public ProblemDetail handleDomainValidation(DomainValidationException ex) {ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());problem.setTitle("Domain Validation Failed");problem.setProperty("invalidFields", ex.getViolations());return problem;}}
spring
Breakdown
1
@RestControllerAdvice
Declares a component for global exception interception across Spring REST controllers.
2
@ExceptionHandler(DomainValidationException.class)
Maps execution control flow to intercept specific business validation exceptions.
3
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());
Instantiates an RFC 7807 compliant error container initialized with HTTP 400 status and detail message.
4
problem.setProperty("invalidFields", ex.getViolations());
Dynamically attaches detailed error domain metadata to the response payload.