Daniela Morais
Daniela Morais

Reputation: 2247

Exceptions with Spring Data Rest

I'm starting on the concepts of microservices with Springboot and Spring Data Rest for me is very confusing how can I do with a few lines of code.
My main question is: I just have entities and repositories, the Spring Data Rest "generates" paths for all the POST requests, GET etc. and my repository performs correctly.
But how do exception handling?
For example, I send a POST without the "name" field and this is accepted but I want to return an error. How do I do that?

Entity

@Document
public class Veiculo{

    @Id
    private String id;

    @Indexed(unique = true)
    private String nome;
    private String tipo;
    @DBRef
    List<Contato> contatos;

    @DBRef
    List<Cliente> clientes;


    public String getId() {
        return this.id;
    }

    public Veiculo setId(String id) {
        this.id = id;
        return this;
    }

    public String getNome() {
        return this.nome;
    }

    public Veiculo setNome(String nome) {
        this.nome = nome;
        return this;
    }

    public String getTipo() {
        return this.tipo;
    }

    public Veiculo setTipo(String tipo) {
        this.tipo = tipo;
        return this;
    }

    public List<Contato> getContatos() {
        return this.contatos;
    }

    public Veiculo setContatos(List<Contato> contatos) {
        this.contatos = contatos;
        return this;
    }

    public List<Cliente> getClientes() {
        return this.clientes;
    }

    public Veiculo setClientes(List<Cliente> clientes) {
        this.clientes = clientes;
        return this;
    }
}

Repository

@RepositoryRestResource(collectionResourceRel = "veiculos", path = "veiculos")
public interface VeiculoRepository extends MongoRepository<Veiculo, String> {
    Veiculo save(Veiculo veiculo);

    List<Veiculo> findAll();

}

Upvotes: 0

Views: 220

Answers (1)

gregturn
gregturn

Reputation: 2693

Why don't you just apply javax.validation.constraints.NotNull to the name parameter? Spring Data REST will apply the validation check and fail if the value is missing.

Upvotes: 2

Related Questions