Cụm bài Exception và xử lý lỗi: 1. Exception trong Java · 2. Custom exception và xử lý lỗi trong Spring Boot
Phần 1 đã đi qua exception ở mức Java core. Trong ứng dụng thật, câu hỏi là: lỗi nghiệp vụ được mô tả bằng exception nào, bắt ở đâu, và trả gì cho client. Đọc xong, bạn thiết kế được custom exception có mã lỗi, gom xử lý lỗi về @RestControllerAdvice, trả ProblemDetail và validate DTO bằng Bean Validation.
1. Custom exception
Ý chính: tách lỗi nghiệp vụ (do mình ném có chủ đích) khỏi lỗi hệ thống, bằng một exception gốc unchecked mang mã lỗi từ enum.
- System exception: do hệ thống, framework, thư viện ném (DB timeout, NPE, lỗi I/O).
- Business/custom exception: do logic của mình ném có chủ đích (email đã được dùng, số dư không đủ, đơn hàng đã huỷ).
Mã lỗi phải ổn định: client dựa vào nó để xử lý, còn message có thể đổi hoặc được dịch.
public enum ErrorCode {
USER_EMAIL_TAKEN(HttpStatus.CONFLICT, "The email is already registered"),
USERNAME_TAKEN(HttpStatus.CONFLICT, "The username is already taken"),
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "User not found"),
ORDER_ALREADY_PAID(HttpStatus.CONFLICT, "Order has already been paid"),
VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "Request is invalid"),
INTERNAL(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
private final HttpStatus status;
private final String defaultMessage;
ErrorCode(HttpStatus status, String defaultMessage) {
this.status = status;
this.defaultMessage = defaultMessage;
}
public HttpStatus status() { return status; }
public String defaultMessage() { return defaultMessage; }
}
public class BusinessException extends RuntimeException {
private final ErrorCode code;
public BusinessException(ErrorCode code) {
super(code.defaultMessage()); // truyền message lên Throwable
this.code = code;
}
public BusinessException(ErrorCode code, String detail) {
super(detail);
this.code = code;
}
public ErrorCode code() { return code; }
}
Góc nhìn thiết kế code của câu hỏi này (vì sao checked exception phá Open-Closed, bọc exception của thư viện ngay tại boundary kèm cause) có ở Clean code: xử lý lỗi, boundary và refactor.
Hai chi tiết khi tự viết exception: cause và serialVersionUID
- Nên có thêm constructor nhận
Throwable cause(super(message, cause)). Khi bọc lỗi hạ tầng (SQLException,IOException) vào exception của mình, cause giữ stack trace gốc. Thiếu nó, log chỉ còn “ném ở đâu” mà mất “vì sao”. - IDE hay cảnh báo thiếu
serialVersionUID, vìThrowableimplementsSerializable. Ứng dụng hiện đại gần như không serialize exception bằng Java serialization (lỗi qua API trả dạng JSON). Khai báoprivate static final long serialVersionUID = 1L;hoặc tắt cảnh báo là đủ.
Gotcha: @Transactional và checked exception
Rollback chỉ hoàn tác được những gì nằm trong database. Method kiểu “save rồi publish” (repo.save(order); kafkaTemplate.send(...)) vẫn có thể lệch: commit xong mà publish lỗi thì service khác không biết đơn tồn tại; publish xong rồi rollback thì họ biết về một đơn không có thật. Cách sửa bằng transactional outbox ở pitfall “dual write” trong bài Message broker và cách chọn broker.
2. Exception trong Spring Boot
Ý chính: controller và service chỉ việc ném exception; một class @RestControllerAdvice bắt tất cả và trả về cùng một format ProblemDetail, kèm mức log đúng.
Đường đi của request qua DispatcherServlet, nơi exception từ handler được chuyển cho @ControllerAdvice, có ở Spring MVC: DispatcherServlet, controller và view.
Vấn đề của try-catch ở mọi nơi
@PostMapping("/users")
public ResponseEntity<?> create(@RequestBody CreateUserRequest req) {
try {
return ResponseEntity.ok(userService.create(req));
} catch (BusinessException e) {
return ResponseEntity.status(409).body(e.getMessage());
} catch (Exception e) {
log.error("create user failed", e);
return ResponseEntity.status(500).body("error");
}
}
Nhân đoạn này lên 50 endpoint: lặp code, mỗi người một format lỗi, dễ quên log, dễ lộ thông tin.
@ControllerAdvice và @ExceptionHandler
@ExceptionHandler(X.class): method xử lý exception kiểuX(và lớp con).@ControllerAdvice: class chứa handler dùng chung cho mọi controller.@RestControllerAdvice=@ControllerAdvice+@ResponseBody.
flowchart LR
C[Client] --> DS[DispatcherServlet]
DS --> Ctrl[Controller]
Ctrl --> Svc[Service]
Svc -- throw BusinessException --> Ctrl
Ctrl -- exception bay ra --> DS
DS --> HER[ExceptionHandlerExceptionResolver]
HER --> Adv["@RestControllerAdvice<br/>chọn @ExceptionHandler khớp nhất"]
Adv -- ProblemDetail JSON --> C
Thứ tự chọn handler:
- Handler đặt ngay trong controller thắng handler trong advice.
- Nhiều advice:
@Orderquyết định. - Trong một class: handler có kiểu khớp gần nhất theo cây kế thừa (không phụ thuộc thứ tự khai báo).
ProblemDetail (RFC 9457)
Từ Spring 6 / Boot 3, Spring hỗ trợ sẵn ProblemDetail: format lỗi chuẩn RFC 9457 (thay RFC 7807), content type application/problem+json.
{
"type": "https://api.example.com/errors/user-email-taken",
"title": "Conflict",
"status": 409,
"detail": "The email is already registered",
"instance": "/api/users",
"code": "USER_EMAIL_TAKEN",
"traceId": "6f1c2a9e8b7d4c10"
}
Field chuẩn: type, title, status, detail, instance. Được thêm field mở rộng như code, traceId, errors.
Bật spring.mvc.problemdetails.enabled=true để exception có sẵn của Spring MVC (sai method, thiếu param, body sai JSON…) tự trả ProblemDetail. Hoặc tự kế thừa ResponseEntityExceptionHandler, như handler dưới đây với ba tầng: lỗi nghiệp vụ, lỗi validate, lưới an toàn.
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
// 1. Lỗi nghiệp vụ: lỗi "dự kiến", log mức WARN/INFO, không cần stack trace
@ExceptionHandler(BusinessException.class)
ProblemDetail handleBusiness(BusinessException ex, HttpServletRequest req) {
ErrorCode code = ex.code();
log.info("Business error {} on {}: {}", code, req.getRequestURI(), ex.getMessage());
ProblemDetail pd = ProblemDetail.forStatusAndDetail(code.status(), ex.getMessage());
pd.setType(URI.create("https://api.example.com/errors/" + code.name().toLowerCase().replace('_', '-')));
pd.setProperty("code", code.name());
return pd;
}
// 2. Lỗi validate @RequestBody: ghi đè hook có sẵn của ResponseEntityExceptionHandler
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request is invalid");
pd.setProperty("code", ErrorCode.VALIDATION_FAILED.name());
pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of("field", fe.getField(),
"message", Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid")))
.toList());
return ResponseEntity.badRequest().body(pd);
}
// 3. Lưới an toàn cuối cùng: log ERROR kèm stack trace, KHÔNG trả chi tiết cho client
@ExceptionHandler(Exception.class)
ProblemDetail handleUnknown(Exception ex, HttpServletRequest req) {
log.error("Unhandled error on {} {}", req.getMethod(), req.getRequestURI(), ex);
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong, please try again later");
pd.setProperty("code", ErrorCode.INTERNAL.name());
return pd;
}
}
Lưới này bắt Exception, không bắt Error: OutOfMemoryError vẫn văng qua. Còn pod bị OOMKilled thì kernel giết process bằng SIGKILL, không handler hay dòng log nào kịp chạy. Hai trường hợp khác nhau ra sao và cách đặt memory limit cho JVM xem ở Bộ nhớ ảo, page cache và JVM trong container.
Thiết kế error response
- Không trả chi tiết nội bộ: không stack trace, SQL, tên class, message của exception hệ thống. Đó là thông tin cho attacker (phiên bản thư viện, cấu trúc bảng). Chi tiết vào log; client nhận message an toàn kèm traceId để đối chiếu.
- Mã lỗi ổn định (
code) để frontend/mobile rẽ nhánh theo logic, không phải so chuỗi message. - Một format duy nhất, kể cả lỗi từ filter/Spring Security. Lỗi xảy ra trước
DispatcherServletkhông đi qua@ControllerAdvice; xử lý bằngAuthenticationEntryPoint,AccessDeniedHandlerhoặc trang lỗi/error. - Log đúng mức: 4xx thường là lỗi client, WARN/INFO là đủ; 5xx log ERROR có stack trace và nên có alert.
- Spring Boot mặc định
server.error.include-stacktrace=nevervàinclude-message=never. Đừng bật ở production.
HTTP status đúng ngữ nghĩa:
| Status | Khi nào |
|---|---|
| 400 | dữ liệu sai |
| 401 / 403 | chưa xác thực / không có quyền |
| 404 | không có tài nguyên |
| 409 | xung đột trạng thái |
| 422 | đúng cú pháp nhưng sai nghiệp vụ (tuỳ team) |
| 429 | quá rate limit |
| 500 / 503 | lỗi server / phụ thuộc bên ngoài đang chết |
Lộ chi tiết lỗi là một mục của A05 Security Misconfiguration trong OWASP Top 10; các mục còn lại ứng với Spring Security thế nào có ở Tấn công web và OWASP Top 10.
traceId trong response phải trùng với log và tracing
traceId chỉ có ích khi nó trùng với id trong log và trong hệ thống tracing. Với OpenTelemetry Java agent, trace_id đã có sẵn trong MDC (bộ key-value gắn với thread đang log), nên handler chỉ cần đọc ra hoặc lấy từ Span.current(), thay vì tự sinh UUID riêng.
Cách trace id đi qua các service bằng header traceparent, và cách in nó vào log, ở bài Distributed tracing với OpenTelemetry.
3. Validate DTO
Ý chính: validate ở nhiều lớp: hình thức ở DTO bằng Bean Validation, nghiệp vụ ở service, và constraint database là chốt chặn cuối. Lỗi validate nên để bay ra global handler, không xử lý trong từng controller.
Bản cho form Thymeleaf (BindingResult, hiện lỗi trên view) có ở form binding và validation trong Spring MVC; DTO record, custom constraint và chuẩn hoá trước khi kiểm trùng có ở DTO, response và validation cho REST API.
Ba lớp validation:
- Biên (DTO): kiểm tra hình thức bằng annotation.
- Service: kiểm tra nghiệp vụ (username đã tồn tại chưa).
- Database: NOT NULL, UNIQUE, FK, CHECK là chốt chặn cuối.
Các tầng trong một project Spring Boot
Bảng trách nhiệm từng tầng: Controller, DTO, Service, Repository, Entity
| Tầng | Trách nhiệm |
|---|---|
| Controller | Nhận request, map endpoint, chuyển đổi DTO, gọi service |
| DTO | Chở dữ liệu giữa các tầng/qua API, tránh lộ field nhạy cảm của entity |
| Service | Logic nghiệp vụ, transaction, gọi repository |
| Repository | Truy vấn, thao tác dữ liệu |
| Entity | Ánh xạ bảng trong database |
Bean Validation với spring-boot-starter-validation
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Starter này kéo Hibernate Validator (implementation của Jakarta Bean Validation, chuẩn annotation để khai báo luật hợp lệ). Từ Spring Boot 2.3 nó không còn nằm sẵn trong spring-boot-starter-web, phải thêm riêng.
Hay dùng nhất: @NotNull, @NotBlank, @Size, @Min/@Max, @Email, @Pattern, @Past, và @Valid để validate tiếp object lồng bên trong.
Bảng đầy đủ annotation Bean Validation
| Annotation | Kiểm tra |
|---|---|
@NotNull |
khác null |
@NotEmpty |
khác null và không rỗng (String, Collection, Map, mảng) |
@NotBlank |
String khác null và có ít nhất một ký tự không phải khoảng trắng |
@Null |
phải là null (ví dụ id khi tạo mới) |
@Size(min, max) |
độ dài String/Collection/Map/mảng |
@Min, @Max |
số nguyên trong khoảng |
@Positive, @PositiveOrZero, @Negative, @NegativeOrZero |
dấu của số |
@Digits(integer, fraction) |
số chữ số phần nguyên/phần thập phân |
@Pattern(regexp) |
khớp regex |
@Email |
định dạng email |
@Past, @PastOrPresent, @Future, @FutureOrPresent |
ngày giờ so với hiện tại |
@AssertTrue, @AssertFalse |
boolean |
@Valid |
validate tiếp object lồng bên trong (cascade) |
@Pattern chạy java.util.regex trên input người dùng, và regex Java không có timeout: pattern viết nhập nhằng là lỗ ReDoS (regex chạy rất lâu với input được chế sẵn). Đặt @Size bên cạnh cũng không chặn được, vì Bean Validation không đảm bảo thứ tự chạy constraint. Cách viết pattern an toàn có ở ReDoS trong Java.
public record CreateUserRequest(
@NotBlank @Size(max = 50) String username,
@NotBlank @Size(min = 10, max = 72) String password, // bcrypt chỉ dùng 72 byte đầu
@NotBlank @Email String email,
@NotNull @Past LocalDate birthDate,
@Valid @NotNull AddressDto address,
@Size(max = 5) List<@NotBlank String> tags // validate từng phần tử
) {}
Hai cách xử lý khi validate thất bại
Cách 1: tham số BindingResult ngay sau tham số được validate. Khi có nó, Spring không ném exception mà để controller tự xử lý.
@PostMapping("/users")
public ResponseEntity<?> create(@Valid @RequestBody CreateUserRequest req, BindingResult result) {
if (result.hasErrors()) {
Map<String, String> errors = result.getFieldErrors().stream()
.collect(Collectors.toMap(FieldError::getField,
fe -> Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid"),
(first, second) -> first));
return ResponseEntity.badRequest().body(errors);
}
return ResponseEntity.status(HttpStatus.CREATED).body(userService.create(req));
}
Cách 2: để exception bay ra global handler (override handleMethodArgumentNotValid như ở mục 2).
Validate @PathVariable và @RequestParam
Đặt constraint thẳng lên tham số:
@GetMapping("/users/{id}")
public UserResponse get(@PathVariable @Positive long id,
@RequestParam(defaultValue = "20") @Max(100) int size) { ... }
Cách hoạt động khác theo phiên bản, nên “làm tương tự DTO” như tài liệu nói là chưa đủ:
| Phiên bản | Điều kiện | Exception khi sai | Mặc định trả |
|---|---|---|---|
| Spring 6.0 trở về trước | Phải có @Validated trên class controller (method validation qua AOP proxy) |
ConstraintViolationException |
500 nếu không tự handle |
| Spring 6.1+ (Boot 3.2+) | Built-in method validation, không cần @Validated |
HandlerMethodValidationException |
400 |
Nếu đang dùng kiểu cũ, nhớ thêm handler map ConstraintViolationException sang 400.
Validate thủ công
Chỉ tự viết validate khi thư viện không làm được: cần gọi hệ thống khác, hoặc tra database (username đã tồn tại).
@Transactional
public UserResponse create(CreateUserRequest req) {
if (userRepository.existsByUsername(req.username())) {
throw new BusinessException(ErrorCode.USERNAME_TAKEN);
}
try {
return UserResponse.from(userRepository.saveAndFlush(User.from(req)));
} catch (DataIntegrityViolationException e) {
// Hai request song song cùng qua được bước exists: UNIQUE constraint là chốt chặn thật
throw new BusinessException(ErrorCode.USERNAME_TAKEN);
}
}
Hai điểm senior cần thấy:
@Validtrên tham số của method trong service không tự chạy. Service phải có@Validatedở class để Spring tạo proxy làm method validation; sai thì némConstraintViolationException. Vì là proxy, gọi nội bộ (this.create(...)) bỏ qua validation.
Có thể tự viết constraint riêng (annotation gắn @Constraint + class implement ConstraintValidator) cho luật dùng lại nhiều lần, ví dụ @StrongPassword, @PhoneVN, hoặc constraint mức class kiểu “endDate phải sau startDate”.
Bài tập
Bài 1: Tài khoản ngân hàng với checked và unchecked custom exception
Đề (diễn đạt lại, Lab 08 của tài liệu Hỏi Dân IT): viết chương trình mở tài khoản ngân hàng rồi rút tiền. Cần hai exception tự định nghĩa:
- một checked khi số tiền rút lớn hơn số dư;
- một unchecked khi mật khẩu ngắn hơn 6 ký tự.
Class BankAccount có username, password, balance; constructor kiểm tra mật khẩu, withdraw(amount) kiểm tra số dư, trừ tiền và in số dư còn lại. main đọc username, password, số dư ban đầu và số tiền rút, bắt cả hai exception, và luôn in “Giao dịch kết thúc.” ở cuối.
Đề đặt tên exception checked là NegativeBalanceException; mình đổi thành InsufficientBalanceException vì số dư không hề âm, thứ bị thiếu là tiền. Tên exception nên nói đúng chuyện gì đã xảy ra.
Lời giải Bài 1: code, output và cách senior cải thiện
import java.util.Scanner;
public class BankApp {
// Checked: caller phải xử lý, vì rút quá số dư là tình huống nghiệp vụ có thể xảy ra
static class InsufficientBalanceException extends Exception {
private final double balance;
private final double requested;
InsufficientBalanceException(double balance, double requested) {
super("Không đủ số dư để rút tiền: số dư " + balance + ", cần rút " + requested);
this.balance = balance;
this.requested = requested;
}
double shortfall() { return requested - balance; }
}
// Unchecked: dữ liệu đầu vào sai, là con của IllegalArgumentException cho đúng ngữ nghĩa
static class WeakPasswordException extends IllegalArgumentException {
WeakPasswordException(int minLength) {
super("Mật khẩu phải có ít nhất " + minLength + " ký tự.");
}
}
static class BankAccount {
static final int MIN_PASSWORD_LENGTH = 6;
private final String username;
private final String password; // demo; app thật chỉ lưu hash
private double balance;
BankAccount(String username, String password, double balance) {
if (password == null || password.length() < MIN_PASSWORD_LENGTH) {
throw new WeakPasswordException(MIN_PASSWORD_LENGTH);
}
if (balance < 0) {
throw new IllegalArgumentException("Số dư ban đầu không được âm: " + balance);
}
this.username = username;
this.password = password;
this.balance = balance;
}
void withdraw(double amount) throws InsufficientBalanceException {
if (amount <= 0) {
throw new IllegalArgumentException("Số tiền rút phải lớn hơn 0: " + amount);
}
if (amount > balance) {
throw new InsufficientBalanceException(balance, amount);
}
balance -= amount;
System.out.println("Rút tiền thành công. Số dư còn lại: " + balance);
}
double balance() { return balance; }
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
System.out.print("Nhập username: ");
String username = in.nextLine().trim();
System.out.print("Nhập password: ");
String password = in.nextLine();
System.out.print("Nhập số dư: ");
double balance = Double.parseDouble(in.nextLine().trim());
System.out.print("Nhập số tiền cần rút: ");
double amount = Double.parseDouble(in.nextLine().trim());
BankAccount account = new BankAccount(username, password, balance);
account.withdraw(amount);
} catch (WeakPasswordException e) {
System.out.println("WeakPasswordException: " + e.getMessage());
} catch (InsufficientBalanceException e) {
System.out.println("InsufficientBalanceException: " + e.getMessage()
+ " (thiếu " + e.shortfall() + ")");
} catch (NumberFormatException e) {
System.out.println("Số tiền không hợp lệ: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Dữ liệu không hợp lệ: " + e.getMessage());
} finally {
System.out.println("Giao dịch kết thúc.");
}
}
}
Ba trường hợp của đề, chạy với JDK 21 (java BankApp.java):
Nhập username: hoidanit
Nhập password: 123456
Nhập số dư: 5000
Nhập số tiền cần rút: 3000
Rút tiền thành công. Số dư còn lại: 2000.0
Giao dịch kết thúc.
Nhập username: hoidanit
Nhập password: 123
Nhập số dư: 5000
Nhập số tiền cần rút: 3000
WeakPasswordException: Mật khẩu phải có ít nhất 6 ký tự.
Giao dịch kết thúc.
Nhập username: hoidanit
Nhập password: 123456
Nhập số dư: 2000
Nhập số tiền cần rút: 3000
InsufficientBalanceException: Không đủ số dư để rút tiền: số dư 2000.0, cần rút 3000.0 (thiếu 1000.0)
Giao dịch kết thúc.
Hai trường hợp đề không nhắc: nhập số dư abc thì in Số tiền không hợp lệ: For input string: "abc"; rút -5 thì in Dữ liệu không hợp lệ: Số tiền rút phải lớn hơn 0: -5.0. Cả hai đều kết thúc bằng “Giao dịch kết thúc.”.
Giải thích:
InsufficientBalanceException extends Exceptionlà checked:withdrawbắt buộc khai báothrows,mainkhông compile nếu quên bắt. Exception mangbalancevàrequestedđể caller tính số tiền thiếu (shortfall()) mà không phải parse message.WeakPasswordException extends IllegalArgumentException: vẫn unchecked (IllegalArgumentExceptionlà con củaRuntimeException) và đúng ngữ nghĩa “dữ liệu đầu vào sai”; code đangcatch (IllegalArgumentException e)cũng bắt được.- Thứ tự
catch:WeakPasswordExceptionvàNumberFormatExceptionđều là con củaIllegalArgumentExceptionnên phải đứng trước nó, nếu không compiler báo “exception has already been caught”. - Constructor ném exception thì object không được tạo, nên không bao giờ có
BankAccountmang mật khẩu yếu hay số dư âm. Đó là cách class tự giữ invariant (điều luôn đúng với object). finallyin “Giao dịch kết thúc.” trong mọi trường hợp, kể cả khi nhập sai số.
Senior sẽ cải thiện gì:
- Không dùng
doublecho tiền:0.1 + 0.2ra0.30000000000000004. DùngBigDecimal(so sánh bằngcompareTo, không dùngequals) hoặclongtheo đơn vị nhỏ nhất (đồng, cent). - Không giữ mật khẩu dạng chữ: chỉ lưu hash (BCrypt, Argon2). Luật độ dài mật khẩu thuộc tầng validate đầu vào (
@Size(min = ...)trên DTO, xem mục 3), không nằm trong object tài khoản. - Checked hay unchecked: trong ứng dụng Spring, “không đủ số dư” thường là
BusinessExceptionunchecked mang mã lỗi (INSUFFICIENT_BALANCE, trả 409 hoặc 422), xử lý ở global handler. Checked hợp với bài tập này vì nó buộc người học thấy luật “catch or declare”. - Đồng thời: hai lệnh rút cùng lúc có thể cùng qua bước kiểm tra số dư (check-then-act) rồi cùng trừ. Trong một JVM phải khoá; nhiều instance thì để database bảo đảm:
UPDATE account SET balance = balance - ? WHERE id = ? AND balance >= ?rồi kiểm tra số dòng bị ảnh hưởng (xem race condition). - Thêm constructor nhận
causecho exception, và viết unit test cho cả ba nhánh (thành công, mật khẩu yếu, thiếu tiền) thay vì thử tay.
Bài 2: Validate trong pet project
Đề (diễn đạt lại): trong pet project, dùng annotation của spring-boot-starter-validation để validate input; minh hoạ cả hai cách xử lý lỗi: BindingResult cho khoảng 10 API, @ExceptionHandler cho phần còn lại.
Lời giải Bài 2: helper dùng chung và test
- Tạo request DTO dạng
recordcho từng endpoint, gắn constraint nhưCreateUserRequestở trên; dùng@Validcho object lồng và phần tử list. - Với 10 API dùng
BindingResult: viết một helper chung chuyểnBindingResultthành cùng format lỗi với global handler, tránh mỗi API trả một kiểu.
public final class ValidationErrors {
private ValidationErrors() {}
public static ResponseEntity<ProblemDetail> badRequest(BindingResult result) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request is invalid");
pd.setProperty("code", "VALIDATION_FAILED");
pd.setProperty("errors", result.getFieldErrors().stream()
.map(fe -> Map.of("field", fe.getField(),
"message", Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid")))
.toList());
return ResponseEntity.badRequest().body(pd);
}
}
- Các API còn lại: chỉ cần
@Valid @RequestBody, đểGlobalExceptionHandler.handleMethodArgumentNotValidxử lý. Thêm constraint cho@PathVariable/@RequestParamvà handler tương ứng (HandlerMethodValidationExceptionhoặcConstraintViolationExceptiontuỳ phiên bản). - Viết test
@WebMvcTestcho mỗi kiểu: gửi body thiếu field, kiểm tra status 400 vàerrors[*].field.
Làm xong bạn sẽ tự thấy vì sao cách 2 thắng: controller gọn, format lỗi thống nhất.
Ghi nhớ
- Giải thích được vì sao lỗi nghiệp vụ nên là unchecked và mang mã lỗi ổn định.
- Biết
@Transactionalrollback với loại exception nào, và cách đổi mặc định. - Vẽ được đường đi của exception từ service tới
@RestControllerAdvice, và biết lỗi nào không đi qua đường đó. - Liệt kê được field của
ProblemDetailvà những thứ không bao giờ trả cho client. - Giải thích được vì sao
existsByUsernamerồi insert là chưa đủ, và chốt chặn thật là gì.
Câu hỏi phỏng vấn
Junior
Vì sao nên dùng @RestControllerAdvice thay vì try-catch trong từng controller?
Để xử lý lỗi ở một chỗ, trả một format thống nhất cho toàn API.
Try-catch ở mọi endpoint lặp code, mỗi người trả một format, dễ quên log và lộ message nội bộ. Với @RestControllerAdvice, controller và service chỉ việc ném; một class quyết định exception nào map sang status nào, body ra sao, log mức nào.
Mid
Một method @Transactional ném checked exception thì transaction có rollback không?
Không. Mặc định chỉ rollback với RuntimeException và Error.
Dùng rollbackFor = Exception.class hoặc chuyển sang unchecked.
@ControllerAdvice hoạt động thế nào, Spring chọn handler nào khi có nhiều handler khớp?
ExceptionHandlerExceptionResolver tìm handler trong controller trước, rồi tới các advice theo @Order; trong một class, kiểu exception gần nhất thắng.
Exception bay ra khỏi controller tới DispatcherServlet, resolver này nhận xử lý. “Gần nhất” là theo cây kế thừa, không theo thứ tự khai báo.
Vì sao không nên trả stack trace hay message của exception hệ thống cho client?
Vì nó lộ thông tin nội bộ cho attacker và vô nghĩa với người dùng.
Thông tin bị lộ: thư viện, phiên bản, cấu trúc DB, đường dẫn. Trả message an toàn + mã lỗi + traceId; chi tiết ghi vào log.
@Valid và @Validated khác nhau thế nào?
@Valid là chuẩn Jakarta, kích hoạt validate và cascade vào object lồng; @Validated của Spring thêm validation group và method validation.
@Validated đặt ở class bật method validation qua AOP proxy: cần cho service, và cho tham số đơn của controller trước Spring 6.1.
Exception ném ra trong servlet filter hoặc Spring Security có tới @ControllerAdvice không?
Không. Filter chạy trước DispatcherServlet, còn @ControllerAdvice chỉ xử lý exception từ handler mà DispatcherServlet gọi.
- Lỗi xác thực và phân quyền:
AuthenticationEntryPointvàAccessDeniedHandler. - Lỗi khác trong filter: tự viết response trong filter, hoặc để rơi về trang lỗi
/error(BasicErrorController). - Đường nào cũng nên trả cùng format
ProblemDetailvới phần còn lại của API.
Senior
Khi nào bạn chọn checked exception trong code hiện đại?
Khi caller thực sự có thể và nên phục hồi, và quên xử lý là nguy hiểm, ví dụ thư viện cấp thấp (I/O).
Trong ứng dụng Spring, lỗi nghiệp vụ thường để unchecked và xử lý tập trung, vì checked làm nhiễu mọi tầng, không đi qua được lambda/stream và không gây rollback mặc định.
Bạn thiết kế error response cho một hệ thống nhiều service như thế nào?
Một format chung (ProblemDetail, RFC 9457) cho mọi service và mọi đường lỗi, kèm mã lỗi ổn định và traceId.
- Field:
type,title,status,detail+codecho client,traceIdđể tra log phân tán,errorscho lỗi theo field. - HTTP status đúng ngữ nghĩa. Lỗi từ filter/security cũng dùng format đó.
- Gọi service khác thì map lỗi của downstream thành lỗi của mình, không chuyển tiếp nguyên văn.
Kiểm tra “username đã tồn tại” bằng existsByUsername rồi mới insert có vấn đề gì?
Race condition check-then-act: hai request đồng thời đều qua bước kiểm tra.
Phải có UNIQUE constraint ở DB và bắt DataIntegrityViolationException để trả 409. Bước kiểm tra trước chỉ để báo lỗi sớm, rõ ràng.
Từ vựng tiếng Anh
| Term | Phát âm | Nghĩa | Ví dụ câu trong phỏng vấn |
|---|---|---|---|
| global exception handler | /ˈɡloʊbəl/ | bộ xử lý lỗi tập trung | “We use a global exception handler so every endpoint returns the same error format.” |
| error response | /ˈɛrər rɪˈspɒns/ | phản hồi lỗi | “Our error response includes a stable error code and a trace ID.” |
| leak | /liːk/ | làm lộ | “Returning raw exception messages can leak internal details.” |
| validation | /ˌvælɪˈdeɪʃən/ | kiểm tra hợp lệ | “Input validation happens at the boundary; business rules live in the service.” |
| constraint | /kənˈstreɪnt/ | ràng buộc | “The unique constraint is the real guarantee against duplicates.” |
| race condition | /reɪs kənˈdɪʃən/ | tranh chấp đồng thời | “Check-then-insert has a race condition under concurrent requests.” |
| rollback | /ˈroʊlbæk/ | hoàn tác giao dịch | “By default Spring only rolls back on unchecked exceptions.” |
| fail fast | /feɪl fæst/ | báo lỗi sớm | “We validate early to fail fast before touching the database.” |
| status code | /ˈsteɪtəs koʊd/ | mã trạng thái HTTP | “A duplicate email returns status code 409, not 500.” |
| trace ID | /treɪs aɪ diː/ | mã truy vết của request | “The client gets a trace ID to send to support, and we look it up in the logs.” |
Ghi chép dựa trên khoá Fundamentals of Backend (Ronin Engineer) và tài liệu Java Core của Hỏi Dân IT, cộng thêm kiến thức tự tìm hiểu, viết lại theo cách hiểu của mình.