3 new user post questions with spring boot

Asked

Viewed 269 times

1

am having the following questions when saving a user in an api using spring boot.

1)The best way to check if the email already exists is this?

2)in case I am sending the id of the user that has just been saved, but it is not being sent as json, just sending the value. How do I send as json? Obs: if I send the whole user it goes in json format

3)how to capture an error when saving the user? so I can treat it or send an error status

@PostMapping
    public ResponseEntity<?> novoUsuario(@RequestBody Usuario usuario){
        //Se o email já existir eu retorno um status de erro
        if(usuarioRepository.findByEmail(usuario.getEmail()) != null) {
            return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
        }
        usuarioRepository.save(usuario);
        return new ResponseEntity<>(usuario.getId(),HttpStatus.OK);
    }

1 answer

1


1 - Best form is very relative. There are n ways to do this, each with a different purpose. If what you’ve done serves you, keep it the way it is.

2 - It is not being serialized because it is a simple value. You can encapsulate this id in a POJO to serialize it as json:

class Model {

    Long id;

    Model(Long id) {
        this.id = id;
    }
}
return new ResponseEntity<>(new Model(usuario.getId()),HttpStatus.OK);

3 - If you want to handle errors at method level, use a Try/catch:

try {
    usuarioRepository.save(usuario);
} catch(Exception e) {
    // tratar excecao
} 

If you want to handle errors at controller level, use a method annotated with @ExceptionHandler:

public class FooController{

    //...
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {
        //
    }
}

If you want to handle errors at the application level, use the annotation @ControllerAdvice:

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}

This article from the Spring blog talks about dealing with errors in framekwork.

  • Thank you very much, and thank you for presenting various ways to treat the error, I will study all of them

Browser other questions tagged

You are not signed in. Login or sign up in order to post.