From 0a529015bc7933bcd724a5ae92605f0e9ee0e3f7 Mon Sep 17 00:00:00 2001 From: bijomutta Date: Fri, 14 Jul 2023 11:21:07 +0200 Subject: [PATCH] handling Null pointer Exception on OwnerID --- .../samples/petclinic/owner/PetController.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java index c3334bab87c..0c0058f3a79 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetController.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetController.java @@ -56,13 +56,23 @@ public Collection populatePetTypes() { @ModelAttribute("owner") public Owner findOwner(@PathVariable("ownerId") int ownerId) { - return this.owners.findById(ownerId); + + Owner owner = this.owners.findById(ownerId); + if (owner == null) { + throw new IllegalArgumentException("Owner ID not found: " + ownerId); + } + return owner; } @ModelAttribute("pet") public Pet findPet(@PathVariable("ownerId") int ownerId, @PathVariable(name = "petId", required = false) Integer petId) { - return petId == null ? new Pet() : this.owners.findById(ownerId).getPet(petId); + + Owner owner = this.owners.findById(ownerId); + if (owner == null) { + throw new IllegalArgumentException("Owner ID not found: " + ownerId); + } + return petId == null ? new Pet() : owner.getPet(petId); } @InitBinder("owner")