Một trong những lý do phổ biến nhất khiến bài nộp đồ án Java Backend bị trả về ở buổi review Pull Request 1-1 không nằm ở việc code không chạy, mà ở cách ứng dụng phản ứng khi có sự cố. Chỉ cần gửi thiếu một trường JSON, trùng email đăng ký hoặc database tạm thời rớt kết nối, API lập tức ném nguyên đoạn stack trace dài 80 dòng ra màn hình client, hoặc tệ hơn là trả về HTTP 200 OK kèm chuỗi "Co loi xay ra" do một khối try-catch nuốt trọn ngoại lệ.

Khi AI coding tools giúp sinh code CRUD nhanh hơn trước, nghịch lý đang diễn ra ở nhiều đội ngũ kỹ thuật là số lượng Pull Request tăng nhanh nhưng thời gian review lại kéo dài đáng kể. Phần lớn thời gian đó không dùng để sửa cú pháp, mà để dọn những khối catch (Exception e) chung chung và vá các điểm rò rỉ thông tin database mà công cụ sinh code tự động chèn vào.

Nếu bạn đang học theo lộ trình từ Java Core OOP, SQL/JDBC lên Spring Boot REST API và triển khai thật bằng Docker, việc làm chủ kiến trúc xử lý lỗi là ranh giới rõ nhất giữa code chạy thử trên máy cá nhân và code đủ chuẩn đưa vào môi trường thật. Đặc biệt khi Spring Boot 4.2.0 vừa phát hành ngày 19/11/2026 và nhánh Spring Boot 4.0 sẽ hết vòng đời hỗ trợ vào ngày 31/12/2026, các dự án mới cần bám sát chuẩn ProblemDetail (RFC 9457) và cấu hình observability ngay từ đầu.

1. Bắt đầu từ Java Core OOP: Đừng dùng Exception như một biến cờ

Lỗi cơ bản nhất khi mới học OOP là ném RuntimeException("Khong tim thay user") ở mọi tầng, hoặc bắt Exception tổng quát rồi trả về null. Khi làm như vậy, tầng Controller không thể phân biệt đâu là lỗi do người dùng nhập sai dữ liệu (HTTP 400), đâu là xung đột trạng thái nghiệp vụ (HTTP 409) và đâu là lỗi sập kết nối database (HTTP 500).

Cách làm gọn và rõ ràng là định nghĩa một phân cấp Domain Exception kế thừa từ RuntimeException, mang theo mã lỗi ổn định để frontend hoặc đối tác tích hợp đọc được thay vì phải parse chuỗi tiếng Việt.

package com.vcoderlog.order.exception;

import org.springframework.http.HttpStatus;

public abstract class BusinessException extends RuntimeException {

    private final String errorCode;
    private final HttpStatus status;

    protected BusinessException(String errorCode, HttpStatus status, String message) {
        super(message);
        this.errorCode = errorCode;
        this.status = status;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public HttpStatus getStatus() {
        return status;
    }
}

Từ lớp nền này, bạn tách các trường hợp nghiệp vụ cụ thể vào từng class riêng thay vì dồn hết vào một kiểu lỗi:

// ResourceNotFoundException.java
package com.vcoderlog.order.exception;

import org.springframework.http.HttpStatus;

public class ResourceNotFoundException extends BusinessException {
    public ResourceNotFoundException(String resource, Object id) {
        super(
            "RESOURCE_NOT_FOUND",
            HttpStatus.NOT_FOUND,
            String.format("%s voi ma %s khong ton tai", resource, id)
        );
    }
}
// DuplicateEmailException.java
package com.vcoderlog.order.exception;

import org.springframework.http.HttpStatus;

public class DuplicateEmailException extends BusinessException {
    public DuplicateEmailException(String email) {
        super(
            "EMAIL_ALREADY_EXISTS",
            HttpStatus.CONFLICT,
            "Email nay da duoc su dung: " + email
        );
    }
}

Thiết kế này giữ cho tầng Service hoàn toàn độc lập với HTTP Servlet hay JSON format, trong khi vẫn truyền đủ ngữ cảnh lên lớp xử lý tập trung.

2. Xuống tầng SQL/JDBC: Bắt đúng SQLState thay vì để lộ tên bảng

Nhiều sinh viên chuyển từ JDBC thuần sang Spring Data JPA vẫn gặp tình huống dở khóc dở cười: khi hai request cùng tạo tài khoản với một email tại cùng một thời điểm, bước kiểm tra existsByEmail() đều trả về false, rồi một request bị PostgreSQL chặn lại bằng lỗi ràng buộc UNIQUE. Nếu không xử lý SQLException, toàn bộ thông báo kiểu ERROR: duplicate key value violates unique constraint "uk_users_email" sẽ bay thẳng ra response API, làm lộ cấu trúc bảng cho bên ngoài.

Với PostgreSQL (và chuẩn SQL nói chung), bạn có thể kiểm tra trực tiếp SQLState trong JDBC PreparedStatement hoặc bóc tách từ DataIntegrityViolationException của Spring:

  • 23505: Vi phạm ràng buộc UNIQUE (trùng khóa hoặc email).
  • 23503: Vi phạm khóa ngoại FOREIGN KEY (tham chiếu tới bản ghi không tồn tại).
  • 23502: Vi phạm NOT NULL.

Đoạn DAO dùng JDBC thuần dưới đây minh họa cách dịch lỗi database sang Domain Exception có kiểm soát:

package com.vcoderlog.order.dao;

import com.vcoderlog.order.exception.DuplicateEmailException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentJdbcDao {

    private static final String PG_UNIQUE_VIOLATION = "23505";

    public long insertStudent(Connection conn, String fullName, String email) throws SQLException {
        String sql = "INSERT INTO students(full_name, email) VALUES (?, ?) RETURNING id";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, fullName);
            stmt.setString(2, email);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getLong("id");
                }
                throw new IllegalStateException("Insert thanh cong nhung khong tra ve id");
            }
        } catch (SQLException ex) {
            if (PG_UNIQUE_VIOLATION.equals(ex.getSQLState())) {
                throw new DuplicateEmailException(email);
            }
            throw ex;
        }
    }
}

Khi viết DAO theo cách này, lỗi trùng dữ liệu luôn trả về HTTP 409 Conflict sạch sẽ ngay cả dưới áp lực đồng thời cao, còn lỗi thật sự như mất mạng database (08006) vẫn được đẩy lên tầng trên để ghi log và cảnh báo.

3. Lên Spring Boot 4.2 REST API: Chuẩn hóa phản hồi bằng ProblemDetail (RFC 9457)

Thay vì mỗi controller tự chế một kiểu JSON lỗi ({"error": ...}, {"msg": ...}, {"code": -1}), Spring Boot hỗ trợ sẵn ProblemDetail theo chuẩn RFC 9457. Khi kết hợp với @RestControllerAdvice và Bean Validation (@Valid), toàn bộ lỗi đầu vào, lỗi nghiệp vụ và lỗi hệ thống đều quy về một cấu trúc thống nhất.

Trước hết, bật chuẩn ProblemDetail trong application.yml cùng cấu hình OpenTelemetry và Graceful Shutdown của Spring Boot 4.2:

spring:
  application:
    name: vcoderlog-order-api
  mvc:
    problemdetail:
      enabled: true

server:
  shutdown: graceful

management:
  endpoints:
    web:
      exposure:
        include: health,info
  endpoint:
    health:
      probes:
        enabled: true

Sau đó, tạo lớp GlobalExceptionHandler gom toàn bộ luồng xử lý lỗi về một nơi. Lưu ý quan trọng: log chi tiết ngoại lệ ở mức ERROR chỉ ghi vào log server cho lỗi 500, tuyệt đối không nhồi ex.getMessage() của lỗi hạ tầng vào response gửi cho client.

package com.vcoderlog.order.api;

import com.vcoderlog.order.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.URI;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ProblemDetail handleBusiness(BusinessException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(ex.getStatus(), ex.getMessage());
        problem.setTitle(ex.getErrorCode());
        problem.setType(URI.create("https://api.vcoderlog.com/errors/" + ex.getErrorCode().toLowerCase()));
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("path", request.getRequestURI());
        return problem;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail handleValidation(MethodArgumentNotValidException ex, HttpServletRequest request) {
        Map<String, String> fieldErrors = new LinkedHashMap<>();
        for (FieldError err : ex.getBindingResult().getFieldErrors()) {
            fieldErrors.putIfAbsent(err.getField(), err.getDefaultMessage());
        }

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST,
            "Du lieu dau vao khong hop le"
        );
        problem.setTitle("VALIDATION_FAILED");
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("path", request.getRequestURI());
        problem.setProperty("errors", fieldErrors);
        return problem;
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ProblemDetail handleIntegrity(DataIntegrityViolationException ex, HttpServletRequest request) {
        log.warn("Vi pham rang buoc du lieu tai {}: {}", request.getRequestURI(), ex.getMostSpecificCause().getMessage());
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.CONFLICT,
            "Du lieu xung dot voi trang thai hien tai"
        );
        problem.setTitle("DATA_CONFLICT");
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("path", request.getRequestURI());
        return problem;
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {
        log.error("Loi he thong khong mong doi tai {}", request.getRequestURI(), ex);
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR,
            "He thong dang gap su co tam thoi, vui long thu lai sau"
        );
        problem.setTitle("INTERNAL_ERROR");
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("path", request.getRequestURI());
        return problem;
    }
}

Khi gắn thêm module spring-boot-starter-opentelemetry (vốn được Spring Boot 4.2 tích hợp sát với các semantic conventions chuẩn), mọi dòng log.error và ProblemDetail đều dễ dàng đối chiếu theo traceId thay vì phải mò mẫm từng dòng console giữa hàng nghìn request.

4. Đưa lên Docker: Tối ưu khởi động và giữ log sạch khi triển khai thật

Một bẫy rất hay gặp khi mang ứng dụng Spring Boot từ IntelliJ ra chạy trong Docker container là app vừa khởi động chưa xong hoặc vừa bị dừng ngang khi deploy bản mới đã làm rớt loạt request đang xử lý dở.

Spring Boot 4.2.0 cải thiện rõ rệt tốc độ khởi động executable JAR nhờ cơ chế đọc class và resource trực tiếp từ nested JAR, đồng thời hỗ trợ Buildpacks trên nền Ubuntu 26.04 với registry build cache. Nếu bạn viết Dockerfile thủ công theo mô hình multi-stage, hãy giữ lại hai nguyên tắc bắt buộc: chạy bằng user không có quyền root và bật healthcheck trỏ thẳng vào /actuator/health/readiness.

FROM eclipse-temurin:25-jdk AS builder
WORKDIR /workspace
COPY pom.xml .
COPY .mvn .mvn
COPY mvnw .
RUN ./mvnw -B dependency:go-offline
COPY src src
RUN ./mvnw -B package -DskipTests

FROM eclipse-temurin:25-jre
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends curl \
  && rm -rf /var/lib/apt/lists/* \
  && addgroup --system appgroup && adduser --system --ingroup appgroup appuser
COPY --from=builder /workspace/target/*.jar app.jar
USER appuser

EXPOSE 8080
HEALTHCHECK --interval=15s --timeout=3s --start-period=25s --retries=3 \
  CMD curl -fsS http://localhost:8080/actuator/health/readiness || exit 1

ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-jar", "app.jar"]

Kết hợp cùng server.shutdown: graceful ở trên, khi Docker gửi tín hiệu SIGTERM lúc restart container, Spring Boot sẽ ngừng nhận request mới nhưng vẫn đợi các request đang chạy hoàn tất transaction trước khi đóng HikariCP pool, tránh phát sinh các lỗi đứt kết nối giả tạo trong log.

5. Checklist tự kiểm tra trước khi gửi Pull Request Review 1-1

Trước khi mở Pull Request cho mentor hoặc tech lead kiểm tra, bạn hãy tự rà nhanh qua 5 gạch đầu dòng dưới đây:

  • Không còn `e.printStackTrace()` hay `System.out.println`: Mọi ngoại lệ bất thường đều đi qua SLF4J Logger với ngữ cảnh rõ ràng.
  • Không nuốt exception: Không có khối catch (Exception e) { return null; } làm sai lệch trạng thái hệ thống.
  • Tách biệt lỗi 4xx và 5xx: Lỗi nhập liệu và lỗi trùng dữ liệu trả về 400 hoặc 409 với ProblemDetail nhất quán, tuyệt đối không trả về 500 hoặc stack trace.
  • Ràng buộc dữ liệu được chặn hai lớp: Vừa kiểm tra ở @Valid tại DTO đầu vào, vừa xử lý SQLState / DataIntegrityViolationException ở tầng dữ liệu.
  • Có integration test cho luồng lỗi: Dùng RestTestClient (thay thế cho TestRestTemplate đã deprecated trong Spring Boot 4.2) để xác nhận API trả đúng mã HTTP và trường errors khi gửi payload sai.

Tại lớp học thực chiến của VCoderLog ở Hải Phòng, quá trình đi từ Java Core OOP, SQL/JDBC lên Spring Boot REST API và đóng gói Docker luôn gắn liền với các buổi review PR 1-1 ngay trên từng dòng code bạn tự viết. Khi nắm chắc cách kiểm soát lỗi từ biên ngoài vào tận database, bạn sẽ không còn phụ thuộc vào việc chép code mẫu hay phó mặc cho AI sinh code hộ khi bước vào phỏng vấn kỹ thuật.