Bằng ProblemDetail — cài đặt của RFC 9457 (bản kế thừa RFC 7807), trả Content-Type: application/problem+json với các field chuẩn type, title, status, detail, instance cộng field mở rộng tùy ý.
Hai cách dùng:
java
// 1. return ProblemDetail from a handler
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleNotFound(OrderNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
pd.setTitle("Order not found");
pd.setProperty("orderId", ex.getOrderId());
return pd;
}
}properties
# 2. let Spring render built-in MVC exceptions as problem details
spring.mvc.problemdetails.enabled=trueKế thừa ResponseEntityExceptionHandler trong @ControllerAdvice để nhận sẵn handler cho toàn bộ exception chuẩn của Spring MVC (MethodArgumentNotValidException, HttpMessageNotReadableException...) và chỉ override cái nào cần đổi nội dung.
Giá trị thực tế: client và các service khác parse một shape lỗi duy nhất, thay vì mỗi team tự chế {code, message, errors} riêng.