I have an end point that returns json by its id and if it doesn't find it (id doesn't exist) then it should send a Json object saying not found. Here is my attempt.
PetController.java
@GetMapping("{id}")
public ResponseEntity<Pet> getPetById(@PathVariable("id") int petId) {
ResponseEntity<Pet> matchingPet = new ResponseEntity<Pet>(petService.getPetById(petId), HttpStatus.OK);
if(matchingPet != null) {
logger.info("pet found");
return matchingPet;
}
else {
logger.info("pet does not exist");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
PetService.java
public interface PetService {
Pet getPetById(int petId);
}
PetServiceImpl.java
@Service
public class PetServiceImpl implements PetService {
private PetRepository petrepository;
public PetServiceImpl(PetRepository petrepository) {
this.petrepository = petrepository;
}
@Override
public Pet getPetById(int petId) {
Optional<Pet> pet = petrepository.findById(petId);
if (pet.isPresent()) {
return pet.get();
}
else {
return null;
//return new ResponseEntity<Pet>(HttpStatus.NOT_FOUND); I have tried
//this and it doesn't work either and still returns null without the notfound error.
}
}
}
It still only returns null. This seems like a logical error because I have a logger in my controller and even when I search a pet with an invalid id that does not exist, it still prints "pet found".
CodePudding user response:
You are creating the instance in your Controller as follows ResponseEntity<Pet> matchingPet = new ResponseEntity<Pet>(petService.getPetById(petId), HttpStatus.OK);
. Of course matchingPet
will always be not null. Try the following:
@GetMapping("{id}")
public ResponseEntity<Pet> getPetById(@PathVariable("id") int petId) {
Pet matchingPet = petService.getPetById(petId);
if(matchingPet != null) {
logger.info("pet found");
return new ResponseEntity<Pet>(matchingPet, HttpStatus.OK);
}
else {
logger.info("pet does not exist");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}