From 51a1ea2e226e580586847ad39e5feeaecc1177dd Mon Sep 17 00:00:00 2001 From: bijomutta Date: Thu, 13 Jul 2023 20:37:36 +0200 Subject: [PATCH] removed <=0 check for ownerID Handling Null Pointer Exception for Owner ID --- .../samples/petclinic/owner/PetController.java | 15 +++++++++++++-- 1 file changed, 13 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 c3334bab8..5dd6c4003 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,24 @@ class PetController { @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")