I have two applications. A spring-boot web service and another that consumes it. I'm not sure how to handle exceptions and report them back to the client.
The method that exposes the web-service:
//web service com springboot
@PostMapping(value = "/save", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public Pessoa save(@RequestBody Pessoa pessoa) {
// email field is unique, might throw constraint violation...
return pessoaRepository.save(pessoa);
}
and the client application that consumes it (without spring, just javaEE Client API):
public Pessoa savePessoa(Pessoa pessoa) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URL_WS+ "/save");
Entity<Pessoa> data = Entity.entity(pessoa, MediaType.APPLICATION_XML_TYPE);
pessoa = target.request(MediaType.APPLICATION_XML_TYPE).post(data, Pessoa.class);
return pessoa;
}
The email field of Pessoa is unique, and when saving can trigger some constraint violation exception. If there is an exception how can I properly report this to client?
Create a exception class
public class PessoaException extends RuntimeException {
public PessoaException(String exception) {
super(exception);
}
}
change your service code as below :-
@PostMapping(value = "/save", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public Pessoa save(@RequestBody Pessoa pessoa) {
// email field is unique, might throw constraint violation...
try{
Pessoa p = pessoaRepository.save(pessoa);
}catch(Exception e){
throw new PessoaException("Message" + e);
}
return p;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.