แทนที่จะห่อทุก method ของ controller ด้วย try/catch Spring ให้คุณรวมศูนย์การจัดการ error ไว้ในคลาสเดียวที่ประกาศ @ControllerAdvice (หรือ @RestControllerAdvice) method ที่ทำเครื่องหมาย @ExceptionHandler จะดักจับ exception ที่ถูกโยนออกมาจากที่ใดก็ตามใน controller ของคุณ แล้วเปลี่ยนให้เป็น HTTP response ที่สม่ำเสมอ
global handler
{
ApiError {
(, ex.getMessage());
}
ApiError {
ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + + e.getDefaultMessage())
.collect(Collectors.joining());
(, msg);
}
}
