0Pricing
Spring Boot 4 Microservices & REST APIs · บทเรียน

@ControllerAdvice และ @ExceptionHandler

จัดการข้อยกเว้นทั่วทั้งระบบ

@ControllerAdvice และ @ExceptionHandler เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

The Problem with Scattered Try/Catch

Handling errors with try/catch in every controller duplicates code and produces inconsistent responses. Spring MVC offers a centralized model: exception handlers that turn exceptions into clean HTTP responses.

Local @ExceptionHandler

A method annotated @ExceptionHandler inside a controller handles the listed exception types for that controller. It maps an exception to a response.

@RestController
public class OrderController {
    @ExceptionHandler(OrderNotFoundException.class)
    public ResponseEntity<String> handleNotFound(OrderNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}

Going Global with @ControllerAdvice

@ControllerAdvice (or @RestControllerAdvice) hosts exception handlers that apply across all controllers. This centralizes error handling in one class.

@RestControllerAdvice
public class GlobalExceptionHandler {
    // handlers shared by every controller
}

Handling a Domain Exception

Define handlers for your own exceptions, returning the right status and a structured body. The same logic now serves every endpoint.

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiError notFound(ResourceNotFoundException ex) {
        return new ApiError("NOT_FOUND", ex.getMessage());
    }
}

A Consistent Error DTO

Return a uniform error shape so clients can parse failures predictably. Include a code, a human message, and optionally a timestamp and field details.

public record ApiError(
        String code,
        String message,
        Instant timestamp) {
    public ApiError(String code, String message) {
        this(code, message, Instant.now());
    }
}

Handling Validation Errors

Catch MethodArgumentNotValidException to convert Bean Validation failures into a clear, field-by-field response instead of Spring’s default body.

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getFieldErrors()
        .forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
    return errors;
}

A Catch-All Handler

Add a handler for Exception as a safety net, returning 500 with a generic message. Crucially, log the real exception but never leak stack traces to clients.

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiError handleUnexpected(Exception ex) {
    log.error("Unhandled error", ex);
    return new ApiError("INTERNAL_ERROR", "Something went wrong");
}

Handler Selection Order

Spring picks the handler whose exception type most closely matches the thrown exception. A handler for OrderNotFoundException beats one for its superclass, so specific handlers take priority.

Scoping the Advice

You can narrow a @ControllerAdvice to specific packages, annotations, or controller types, allowing different error policies for, say, public vs internal APIs.

@RestControllerAdvice(basePackages = "com.example.api.publicapi")
public class PublicApiExceptionHandler { }

Accessing the Request

Handler methods can accept extra parameters like WebRequest or HttpServletRequest to enrich responses with the path or a correlation id.

@ExceptionHandler(ResourceNotFoundException.class)
public ApiError notFound(ResourceNotFoundException ex, HttpServletRequest req) {
    return new ApiError("NOT_FOUND", ex.getMessage() + " at " + req.getRequestURI());
}

Security: Do Not Over-Share

Error responses are a common information-leak vector. Return enough for clients to act, but never expose internal class names, SQL, or stack traces. Log details server-side instead.

Quick Check

Test your understanding of centralized handling.

Recap

Centralize error handling.

  • @ExceptionHandler maps exceptions to responses
  • @ControllerAdvice applies handlers across all controllers
  • Return a consistent error DTO
  • Handle validation, domain, and catch-all cases
  • Most specific handler wins; never leak internals to clients

คำถามที่พบบ่อย

บทเรียน “@ControllerAdvice และ @ExceptionHandler” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “@ControllerAdvice และ @ExceptionHandler” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “@ControllerAdvice และ @ExceptionHandler”

จัดการข้อยกเว้นทั่วทั้งระบบ คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “@ControllerAdvice และ @ExceptionHandler” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตรวจสอบบีนด้วย @Valid
  2. ตัวตรวจสอบแบบกำหนดเอง
  3. @ControllerAdvice และ @ExceptionHandler
  4. รายละเอียดปัญหา (RFC 7807)
← กลับไปที่ Spring Boot 4 Microservices & REST APIs