如何处理并向客户端Web服务异常报告?

时间:2019-01-18 14:28:14

标签: java rest spring-boot exception-handling client-applications

我有两个申请。一个春季启动的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);               
    }

和使用它的客户端应用程序(没有春季,只有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的电子邮件字段是唯一的,保存时会触发一些违反约束的异常。 如果有例外,我该如何正确地向客户报告?

1 个答案:

答案 0 :(得分:0)

创建异常类

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;               
    }