Thay vì bọc mọi method controller trong try/catch, Spring cho phép bạn tập trung xử lý lỗi vào một class gắn @ControllerAdvice (hoặc @RestControllerAdvice). Các method đánh dấu @ExceptionHandler bắt exception ném ra ở bất kỳ đâu trong controller và biến chúng thành response HTTP nhất quán.
Một handler toàn cục
{
ApiError {
(, ex.getMessage());
}
ApiError {
ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + + e.getDefaultMessage())
.collect(Collectors.joining());
(, msg);
}
}
