Performance: Handling not found exceptions
This affects server response time and user experience by controlling how quickly and cleanly the server handles missing resource requests.
@ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException {} @GetMapping("/resource/{id}") public ResponseEntity<Resource> getResource(@PathVariable String id) { return repository.findById(id) .map(ResponseEntity::ok) .orElseThrow(ResourceNotFoundException::new); }
try { // fetch resource } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred"); }
| Pattern | Server Processing | Response Delay | Network Impact | Verdict |
|---|---|---|---|---|
| Generic Exception Catching | High (extra processing) | Increased by 100-200ms | No impact | [X] Bad |
| Specific NotFound Exception | Low (early exit) | Minimal delay | No impact | [OK] Good |
@GetMapping("/items/{id}")
public Item getItem(@PathVariable Long id) {
return itemRepository.findById(id)
.orElseThrow(() -> new ItemNotFoundException(id));
} @ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(Long id) {
super("Product " + id + " not found");
}
}
@GetMapping("/products/{id}")
public Product getProduct(@PathVariable Long id) {
return productRepo.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
}ResourceNotFoundException occurs. Which approach correctly achieves this?Pass the test and this pattern moves unknown