Spring Boot 4 Microservices & REST APIs · Pelajaran

@ControllerAdvice dan @ExceptionHandler

Tangani eksepsi secara global.

Pelajaran 3 dari 413 langkah

@ControllerAdvice dan @ExceptionHandler adalah pelajaran Spring Boot 4 Microservices & REST APIs gratis di CoddyKit. Ini adalah pelajaran 3 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Spring Boot 4 Microservices & REST APIs, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Spring Boot 4 Microservices & REST APIs mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

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
Gratis untuk memulai

Belajar Java dengan tutor AI — gratis

Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.

Kursus
24
Pelajaran
93

Pertanyaan yang Sering Diajukan

Apakah pelajaran “@ControllerAdvice dan @ExceptionHandler” gratis?

Ya — teks lengkap “@ControllerAdvice dan @ExceptionHandler” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Spring Boot 4 Microservices & REST APIs, upgrade ke CoddyKit PRO. Kursus Spring Boot 4 Microservices & REST APIs mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “@ControllerAdvice dan @ExceptionHandler”?

Tangani eksepsi secara global. Kamu berlatih Spring Boot 4 Microservices & REST APIs dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Spring Boot 4 Microservices & REST APIs?

Tidak diperlukan pengalaman sebelumnya. Spring Boot 4 Microservices & REST APIs di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 3 dari 4.

Berapa lama pelajaran “@ControllerAdvice dan @ExceptionHandler” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Spring Boot 4 Microservices & REST APIs ini?

Ya. Setiap pelajaran Spring Boot 4 Microservices & REST APIs menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Validasi Bean dengan @Valid
  2. Validator Kustom
  3. @ControllerAdvice dan @ExceptionHandler
  4. Detail Masalah (RFC 7807)
← Kembali ke Spring Boot 4 Microservices & REST APIs