java / beginner
Snippet
Throwing ResponseStatusException for Missing Entities
ResponseStatusException provides a straightforward, built-in way to handle programmatic errors in Spring REST controllers. By combining it with Java's Optional.orElseThrow, you can cleanly branch control flow and return an HTTP 404 Not Found response when a requested resource does not exist in the database.
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
Breakdown
1
@GetMapping("/{id}")
Maps HTTP GET requests containing an ID path variable to this handler method.
2
return repository.findById(id)
Queries the database repository, returning an Optional<Product>.
3
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found"));
Extracts the entity if present, or throws a 404 HTTP exception if the Optional is empty.