简体   繁体   English

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

[英]How to handle and report to client Web Service Exceptions?

I have two applications. 我有两个应用程序。 A spring-boot web service and another that consumes it. 一个春季启动的Web服务,另一个使用它的服务。 I'm not sure how to handle exceptions and report them back to the client. 我不确定如何处理异常并将其报告给客户端。

The method that exposes the web-service: 公开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);               
    }

and the client application that consumes it (without spring, just javaEE Client API): 以及使用它的客户端应用程序(没有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;
}

The email field of Pessoa is unique, and when saving can trigger some constraint violation exception. Pessoa的电子邮件字段是唯一的,保存时会触发一些违反约束的异常。 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;               
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM