API cần từ chối dữ liệu sai và trả thông báo lỗi nhất quán. Bài này dùng Bean Validation và @RestControllerAdvice để xử lý lỗi tập trung theo chuẩn ProblemDetail.

45 phútTrung cấp
Bạn sẽ học được
  • @NotBlank, @Size, @Min, @Max, @Email
  • @Valid trên tham số
  • Xử lý lỗi tập trung
  • ProblemDetail (RFC 9457)

Cơ sở lý thuyết

Bean Validation (Jakarta Validation, cài đặt bởi Hibernate Validator) là đặc tả chuẩn khai báo ràng buộc bằng annotation trên trường, tham số. @Valid kích hoạt kiểm tra; vi phạm sinh ngoại lệ MethodArgumentNotValidException.

  • Xử lý lỗi xuyên suốt (cross-cutting concern): thay vì try-catch ở mọi controller, @RestControllerAdvice gom xử lý ngoại lệ vào một nơi – một ứng dụng của lập trình hướng khía cạnh.
  • ProblemDetail (RFC 9457) là định dạng lỗi chuẩn cho API HTTP: type, title, status, detail, instance; máy khách xử lý lỗi thống nhất.
  • Phân biệt lỗi máy khách (4xx – dữ liệu sai, không có quyền) và lỗi máy chủ (5xx – không được để lộ chi tiết nội bộ như stack trace).
  • Ràng buộc tùy chỉnh: tự viết annotation và ConstraintValidator cho quy tắc nghiệp vụ.

Validation

public record SinhVienDto(
    @NotBlank @Pattern(regexp = "SV\\d+") String ma,
    @NotBlank @Size(min = 3, max = 100) String ten,
    @Min(0) @Max(10) double diem,
    @Email String email) {}

@PostMapping
ResponseEntity<?> them(@Valid @RequestBody SinhVienDto dto) { ... }

Xử lý lỗi tập trung

@RestControllerAdvice
class XuLyLoi {
    @ExceptionHandler(KhongTimThayException.class)
    ProblemDetail khongThay(KhongTimThayException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail duLieuSai(MethodArgumentNotValidException e) {
        var pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        pd.setProperty("loi", e.getFieldErrors().stream()
            .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (a, b) -> a)));
        return pd;
    }
}

Ứng dụng thực tế

Bài toán: ràng buộc tùy chỉnh kiểm tra mã số sinh viên đúng định dạng của trường (2 chữ số khóa + mã ngành 3 chữ số + 4 chữ số thứ tự), dùng lại ở mọi DTO:

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MaSvValidator.class)
public @interface MaSinhVien {
    String message() default "Mã sinh viên không hợp lệ";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
class MaSvValidator implements ConstraintValidator<MaSinhVien, String> {
    public boolean isValid(String v, ConstraintValidatorContext c) {
        return v != null && v.matches("\\d{2}\\d{3}\\d{4}");
    }
}
record DangKyDto(@MaSinhVien String maSv, @NotBlank String maLop) {}
Thực hành
  1. Thêm ràng buộc cho DTO sinh viên.
  2. Trả 404 có thông báo khi không tìm thấy.
  3. Gửi dữ liệu sai và xem phản hồi lỗi.
Tóm tắt bài học
  • Annotation khai báo ràng buộc.
  • @Valid kích hoạt kiểm tra.
  • @RestControllerAdvice xử lý lỗi một chỗ.