【问题标题】:How to pass API exception output to through own REST service?如何通过自己的 REST 服务传递 API 异常输出?
【发布时间】:2019-07-01 08:52:27
【问题描述】:

总结: 我想使用我自己的 Rest 服务将一个 REST 服务端点给出的有效异常输出传递给最终用户。

我所做的是,我使用 RestTemplate 类在服务类中调用了该服务,它在有效的发布请求上提供了有效的输出。但是,当我将无效输入传递给它时,我在调用该 API 的服务类中只得到“400 BAD REQUEST”结果。但是当我使用邮递员单独调用该 API 时,我得到了预期的输出。

代码示例:

class Abc {
    ResponseEntity<String> = response;
    static final String url = "https://abc-xyz.com/client-rest-end-point-url";
    public ResponseEntity getDetails(RequestInput requestInput) {

        try{
            response=restTemplate.postForObject(url,requestInput,String.class);
        } catch(Exception e) {
            ResponseEntity response = (ResponseEntity<ErrorModel>)restTemplate.postForEntity(url,requestInput,ErrorModel.class);
        }//try-catch
    }//getDetails method
}//class

【问题讨论】:

  • 对于spring-boot,您可以尝试全局异常@exceptionhandler 来累积所有异常..您可以检查一下..是否有任何问题 ping back
  • But when I am calling that API separately using postman, there I'm getting expected output. 中的预期输出是什么?

标签: java rest exception resttemplate oauth2resttemplate


【解决方案1】:

您可以为整个应用程序创建一个自定义异常类,并且可以使用throw 关键字在JSON 中发送数据 假设你有异常类是:

public class TestException extends Exception {

private static final long serialVersionUID = 1L;
private String code;
private String detailMessage;

public TestException() {
};

public TestException(String message, String code, String detailMessage) {
    super(message);
    this.code = code;
    this.detailMessage = detailMessage;
}

public TestException(String message, String code) {
    super(message);
    this.code = code;
}
//TestExceptionResponseCode is another class for message data, if required.
public TestException(TestExceptionResponseCode testExceptionResponseCode) {
    super(testExceptionResponseCode.getMessage());
    this.code = testExceptionResponseCode.getCode();
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getDetailMessage() {
    return detailMessage;
}

public void setDetailMessage(String detailMessage) {
    this.detailMessage = detailMessage;
}

}

现在在你的情况下抛出异常可能是这样的:

class Abc {
ResponseEntity<String> = response;
static final String url = "https://abc-xyz.com/client-rest-end-point-url";
public ResponseEntity getDetails(RequestInput requestInput) {
       if(requestInput==null){
          throw new TestException("FAILED", "1", "Data can't be null");
    }

}

【讨论】:

    【解决方案2】:

    使用@ExceptionHandler 注释来注释您的方法。您可以在与控制器不同的类中编写代码。

    @ControllerAdvice
    public class YourExceptionHandler {
    
    @ExceptionHandler(CustomException.class)
    public String xException() {
     return "error/exception";
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2016-02-21
      • 2023-04-02
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2018-05-01
      • 2018-11-20
      相关资源
      最近更新 更多