RestTemplate响应中的错误消息始终为“ null”

问题描述 投票:0回答:1

我在这里迷失了方向。我有2台服务器,一台是幕后微服务,一台是调用它的主服务器。

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

@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个回答
0
投票

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

try {
 String fullPath = url + "/Token/getPaymentToken";
 return this.restTemplate.postForObject(fullPath, getPaymentTokenRequest , GetPaymentTokenResponse.class);
}
catch(HttpClientErrorException hcee) {
  if (hcee.getRawStatusCode() == 503) {
    ...
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.