#Java Spring Boot deleteById - Cant reach Exception

13 messages · Page 1 of 1 (latest)

somber compass
#

I'm making a API REST using Java Spring Boot.

One of my services is deleteUser. that delete User by an Id.

userService.java:
public boolean deleteUser(Long id) { try { usuarioRepository.deleteById(id); return true; } catch(Exception err) { return false; } }

I use try catch to manage the exception in case the Id dont exists or is null, but this never happens
Even If i Post id=24535253 its always true.

userController.java
`@DeleteMapping( path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){

    boolean ok = this.usuarioService.deleteUser(id);
    System.out.println("booleando de id: "+ ok);
   if(ok){
        return "Se eliminó el usuario con id " + id;
    }else{
        return "No pudo eliminar el usuario con id" + id;
    }
}`

I'm using JDK 17

true glenBOT
#

This post has been reserved for your question.

Hey @somber compass! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

opal snow
#

Do you ever explicitly throw an exception in your deleteById method?

frank frost
#

From the docs If the entity is not found in the persistence store it is silently ignored.

#

@somber compass

somber compass
#

hmmm

#

I think I need to check if the Id exists or not and them return a boolean.
But dont know how

frank frost
#
if (repository.existsById(entityId)) {
    repository.deleteById(entityId);
}```
somber compass
#

thanx

true glenBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.