java / beginner
Snippet
Auslösen einer ResponseStatusException bei fehlenden Entitäten
ResponseStatusException bietet eine direkte, eingebaute Möglichkeit, programmatische Fehler in Spring-REST-Controllern zu behandeln. In Kombination mit Optional.orElseThrow von Java lässt sich der Kontrollfluss sauber steuern und eine HTTP-404-Not-Found-Antwort zurückgeben, wenn eine angeforderte Ressource nicht existiert.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestController@RequestMapping("/products")public class ProductController {private final ProductRepository repository;public ProductController(ProductRepository repository) {this.repository = repository;}@GetMapping("/{id}")public Product getProductById(@PathVariable Long id) {return repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found"));}}
spring
Erklärung
1
@GetMapping("/{id}")
Weist HTTP-GET-Anfragen mit einer ID-Pfadvariable dieser Handler-Methode zu.
2
return repository.findById(id)
Fragt das Datenbank-Repository ab und liefert ein Optional<Product> zurück.
3
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found"));
Gibt die Entität zurück, falls vorhanden, oder wirft eine 404-HTTP-Exception, wenn das Optional leer ist.