Użyj `@ControllerAdvice` z `@ExceptionHandler`, aby mapować wyjątki na spójne odpowiedzi HTTP (status + body). Dzięki temu kontrolery są czystsze, a obsługa błędów jest w jednym miejscu.
@ControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<String> badRequest(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}Globalna obsługa wyjątków w Spring MVC to najczęściej:
Mapujesz typy wyjątków na odpowiedzi HTTP przez `@ExceptionHandler`. Dla bogatszych odpowiedzi zwracaj `ResponseEntity<?>` (status, header, body) albo użyj `ProblemDetail` w nowszych wersjach Springa.
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<ProblemDetail> badRequest(IllegalArgumentException e) {
var pd = ProblemDetail.forStatus(400);
pd.setTitle("Bad request");
pd.setDetail(e.getMessage());
return ResponseEntity.badRequest().body(pd);
}
}