Delete Mapping Exception in Spring Data

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

Answers (2)

lczapski
lczapski

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

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

Related Questions