0 Tage Serie
java / beginner
Snippet

Zentralisieren der API-Fehlerbehandlung mit ControllerAdvice

Anstatt Ausnahmen in einzelnen Controllern manuell abzufangen, bietet Spring @RestControllerAdvice für anwendungsweite Fehlerbehandlung. Sobald ein Controller eine ItemNotFoundException wirft, leitet Spring diese an die passende @ExceptionHandler-Methode weiter, um einheitliche JSON-Fehlerobjekte mit dem passenden HTTP-Status zurückzugeben.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ItemNotFoundException extends RuntimeException {
public ItemNotFoundException(String message) {
super(message);
}
}
@RestControllerAdvice
public class GlobalApiExceptionHandler {
@ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<Map<String, String>> handleItemNotFound(ItemNotFoundException ex) {
Map<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
response.put("timestamp", LocalDateTime.now().toString());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
}
spring
Erklärung
1
@RestControllerAdvice
Kennzeichnet die Klasse als globalen Abfangdienst für Ausnahmen aus allen REST-Controllern.
2
@ExceptionHandler(ItemNotFoundException.class)
Legt fest, welcher Ausnahmetyp von dieser Methode abgefangen und verarbeitet wird.
3
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
Erstellt und sendet eine benutzerdefinierte HTTP-404-Antwort in Form von JSON-Schlüssel-Wert-Paaren.