3 doubts of new user post with spring boot

1

I have the following doubts when saving a user to an api using spring boot.

1) Is the best way to check if email already exists?

2) In case I am sending the id of the user just saved, but it is not being sent as json, it is only sending the value. How do I submit as json? obs: if I send the entire user it goes in json format

3) how to catch a possible 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);
    }
    
asked by anonymous 01.04.2018 / 04:16

1 answer

1

1 - Best shape is very relative. There are n ways to do this, each with a different purpose. If what you've done is up to 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 the method level, use a try / catch:

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

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

public class FooController{

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

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

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

This Spring article discusses the treatment of errors in framekwork.

    
01.04.2018 / 05:42