@RestControllerAdvice + @ExceptionHandler xử lý exception tập trung — không try/catch rải khắp controller.
java
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
ProblemDetail handleNotFound(EntityNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage());
}
}Tương tự bắt MethodArgumentNotValidException (lỗi @Valid) trả 400 kèm map field→message từ ex.getBindingResult().getFieldErrors(), và Exception.class trả 500 generic (log full stack, không lộ chi tiết ra ngoài).
ProblemDetail (Spring 6, RFC 9457) = format error response chuẩn: type, title, status, detail + property tuỳ biến.
Scope: @ControllerAdvice áp cho mọi controller; thu hẹp bằng @ControllerAdvice(basePackages = "com.example.api").