Reputation: 59
Hello i would like to throw an exception in case the user enters an id that is not existing in the system. This is my mapping
@DeleteMapping("/drugs/{neo4jId}")
public void deleteDrug(@PathVariable Long neo4jId) {
drugsRep.deleteById(neo4jId);
}
what would you suggest? * I dont want to handle it only in my Frontend
Upvotes: 1
Views: 1907
Reputation: 4120
You can try something like this:
if (drugsRep.existsById(neo4jId)) {
throw new EntityNotFoundExceptionById("Invlaid Id was provided");
}
drugsRep.deleteById(neo4jId);
If you define a custom exception you can map it to appropriate http status.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class EntityNotFoundExceptionById extends RuntimeException {
public EntityNotFoundExceptionById(String message) {
super(message);
}
}
Upvotes: 3
Reputation: 94
Good morning, in this case you can check if user exists.
In Spring-mongodb have one function when you extends the MongoRepository with the name of existsById. So take a look in the documentation, maybe your repository have this function too.
And, when you use this function you can throw one exception. Like the code
if(!repository.existsById(id)){
throw new NotFoundException();
}
repository.deleteById(id);
Upvotes: 0