java / intermediate
Snippet
Standardized RFC 7807 Error Responses Using ProblemDetail and ResponseEntityExceptionHandler
Spring 6 / Spring Boot 3 provides native support for RFC 7807 Problem Details. Extending ResponseEntityExceptionHandler and returning ProblemDetail objects produces clean, standardized JSON error responses across REST endpoints.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestControllerAdvicepublic class GlobalApiExceptionHandler extends ResponseEntityExceptionHandler {@ExceptionHandler(ResourceNotFoundException.class)public ProblemDetail handleResourceNotFound(ResourceNotFoundException ex) {ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND,ex.getMessage());problem.setTitle("Resource Not Found");problem.setType(URI.create("https://api.example.com/errors/not-found"));problem.setProperty("timestamp", Instant.now());return problem;}}
spring
Breakdown
1
@RestControllerAdvice
Declares a centralized exception handling component applicable to controllers across the entire application.
2
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
Instantiates an RFC 7807 compliant payload specifying the HTTP status code and human-readable detail message.
3
problem.setProperty("timestamp", Instant.now());
Appends custom metadata keys to the error JSON payload without creating a custom wrapper class.