Handling Null Pointer Exception for Owner ID

This commit is contained in:
bijomutta 2023-07-13 20:37:36 +02:00
parent 3a6127557d
commit 07dd88f9f7

View file

@ -56,13 +56,28 @@ class PetController {
@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")