[英]How to handle and report to client Web Service Exceptions?
我有兩個應用程序。 一個春季啟動的Web服務,另一個使用它的服務。 我不確定如何處理異常並將其報告給客戶端。
公開Web服務的方法:
//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);
}
以及使用它的客戶端應用程序(沒有spring,只有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;
}
Pessoa的電子郵件字段是唯一的,保存時會觸發一些違反約束的異常。 如果有例外,我該如何正確地向客戶報告?
創建一個異常類
public class PessoaException extends RuntimeException {
public PessoaException(String exception) {
super(exception);
}
}
更改您的服務代碼如下:-
@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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.