Approach: centralise error handling with @RestControllerAdvice so every controller returns consistent, safe error responses.
How it works:
- Create a class annotated with @RestControllerAdvice.
- Add @ExceptionHandler methods for specific exception types, for example ResourceNotFoundException mapped to 404 and MethodArgumentNotValidException (bean validation failures) mapped to 400 with field errors.
- Add a fallback handler for Exception that logs the error with a correlation id and returns a generic 500 message without stack traces.
Response format:
- Use a consistent body. Spring 6 / Boot 3 support RFC 7807 ProblemDetail (type, title, status, detail, instance), enabled with spring.mvc.problemdetails.enabled=true or by returning ProblemDetail from handlers.
Good practices:
- Never leak internal messages, SQL or stack traces to clients.
- Map domain exceptions to precise HTTP codes (409 conflict, 422 validation, 403 forbidden).
- Log at the right level: client errors at warn or info, server errors at error.
- Test handlers with @WebMvcTest and MockMvc.