java / beginner
Snippet
Behandlung spezifischer Controller-Ausnahmen mit ExceptionHandler
Die Annotation @ExceptionHandler in Spring fängt spezifische Ausnahmen ab, die von Controller-Methoden geworfen werden, und wandelt Fehler in saubere HTTP-Antworten um.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@RestController@RequestMapping("/users")public class UserController {@GetMapping("/{id}")public String getUser(@PathVariable Long id) {if (id < 1) {throw new IllegalArgumentException("User ID must be positive.");}return "User: " + id;}@ExceptionHandler(IllegalArgumentException.class)public ResponseEntity<String> handleInvalidId(IllegalArgumentException ex) {return ResponseEntity.badRequest().body(ex.getMessage());}}
spring
Erklärung
1
if (id < 1) { throw new IllegalArgumentException(...); }
Prüft die Validierungslogik und löst eine IllegalArgumentException aus, wenn die ID ungültig ist.
2
@ExceptionHandler(IllegalArgumentException.class)
Gibt an, dass diese Handler-Methode jede IllegalArgumentException innerhalb dieses Controllers abfängt.
3
return ResponseEntity.badRequest().body(ex.getMessage());
Erstellt und liefert eine HTTP 400 (Bad Request)-Antwort mit der Fehlermeldung der Ausnahme zurück.