【问题标题】:Error message always "null" from RestTemplate response来自 RestTemplate 响应的错误消息始终为“null”
【发布时间】:2020-10-01 00:46:47
【问题描述】:

我在这里疯了。 我有两台服务器,一台是后台微服务,一台是调用它的主服务器。

在微服务中,我抛出一个异常,定义如下:

@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public class CGTokenException extends Exception{

   // private String msg;

   public CGTokenException() { super("Unknown error getting token / Validating card!"); }

   public CGTokenException(String msg) {super(msg); }
}

在我的主服务器中,我是这样使用它的:

   @Override
    public
    GetPaymentTokenResponse getToken(GetPaymentTokenRequest getPaymentTokenRequest, String url) {

        try {
           String fullPath = url + "/Token/getPaymentToken";
            return this.restTemplate.postForObject(fullPath, getPaymentTokenRequest , GetPaymentTokenResponse.class);
        }
        catch (Exception ex) {
            log.error("Error getting TOKEN / validating card from Credit Guard");
            log.error( "CGTokenController error: " + ex.getMessage() );

            ex.printStackTrace();
        }
}

我只是从微服务内部做 throw new CGTOkenException(msg);

出于某种原因,在我的主服务记录器中,我得到了“503 null”的日志,就像这是抛出错误中的消息(来自log.error( "CGTokenController error: " + ex.getMessage() ); 行)。

但是,如果我将邮递员请求直接发送到我的微服务 - 我会收到包含正确消息的完整错误。

我做错了什么?我想问题是我如何在我的主要服务中捕捉到它......但我就是找不到它是什么。如何传递正确的错误消息以传播到主要服务?

【问题讨论】:

    标签: java spring-boot resttemplate spring-resttemplate


    【解决方案1】:

    您要么需要捕获正确的异常,要么强制转换它。

    try {
     String fullPath = url + "/Token/getPaymentToken";
     return this.restTemplate.postForObject(fullPath, getPaymentTokenRequest , GetPaymentTokenResponse.class);
    }
    catch(HttpClientErrorException hcee) {
      if (hcee.getRawStatusCode() == 503) {
        ...
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2019-02-20
      相关资源
      最近更新 更多