Exception Handling: @ControllerAdvice
Penjelasan
@ControllerAdvice menandai class sebagai penangan exception TERPUSAT untuk SELURUH Controller di aplikasi — method di dalamnya ditandai @ExceptionHandler(TipeException.class), dipanggil OTOMATIS setiap kali exception tipe itu dilempar dari Controller mana pun, tidak perlu try/catch berulang di tiap method.
Contoh Konsep
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return ResponseEntity.unprocessableEntity().body(errors);
}
@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<String> handleNotFound(NoSuchElementException ex) {
return ResponseEntity.notFound().build();
}
}
Praktikum
Buat @ControllerAdvice GlobalExceptionHandler dengan @ExceptionHandler(RuntimeException.class) yang merespons ResponseEntity.internalServerError() berisi map {"error": ex.getMessage()}.
Ketik/edit bebas di sini untuk latihan — kode ini tidak dijalankan.
Tips
@ExceptionHandler yang lebih SPESIFIK (mis. NoSuchElementException) SEBAIKNYA didefinisikan terpisah dari yang lebih UMUM (mis. RuntimeException atau Exception) — Spring Boot memilih handler yang PALING SPESIFIK cocok dengan tipe exception yang benar-benar dilempar, jadi urutan definisi di dalam class tidak masalah, yang penting granularitasnya jelas.