Skip to content

Commit

Permalink
Handling Null Pointer Exception for Owner ID
Browse files Browse the repository at this point in the history
  • Loading branch information
bijomutta committed Jul 13, 2023
1 parent 3a61275 commit 07dd88f
Showing 1 changed file with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,28 @@ public Collection<PetType> populatePetTypes() {

@ModelAttribute("owner")
public Owner findOwner(@PathVariable("ownerId") int ownerId) {
return this.owners.findById(ownerId);

if (ownerId <= 0) {
throw new IllegalArgumentException("Owner ID is required");
}
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);
if (ownerId <= 0) {
throw new IllegalArgumentException("Owner ID is required");
}
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")
Expand Down

0 comments on commit 07dd88f

Please sign in to comment.