【问题标题】:Rest Template pass original Message休息模板传递原始消息
【发布时间】:2019-09-21 16:46:48
【问题描述】:

我正在使用 RestTemplate 构建一个(主要是)通过 API 来查询各种不同的服务。在错误和缺少参数时,目标 API 会传递响应中缺少的错误消息,我想使用相同的 HttpCode 传递这些错误消息。示例:

curl -XPOST sourceapi:/...

{"type":"/errors/failed","title":"Entity Exists","details":"Entity with name \"test\" already exists","status":409}

如果我对 RestTemplate 做同样的事情,它会抛出异常并且消息为 null,它看起来像这样:

curl -XPOST testapi:/...

409 null

如何将错误代码以及那里的对象传递给“客户端”。 (即使记录它也是一个开始......)

我有一个 @ControllerAdvice 类,它已经缓存了它,但消息实际上只是 409 null

  @ExceptionHandler(value = {HttpClientErrorException.class})
  public ResponseEntity<Object> clientErrorException(HttpClientErrorException ex) {
    return ResponseEntity.status(ex.getStatusCode()).body(ex.getMessage());
  }

有没有办法在使用 RestTemplateBuilder 构建模板时添加 ErrorParser 或其他东西?

【问题讨论】:

标签: spring-boot spring-mvc resttemplate


【解决方案1】:

getResponseBodyAsString() 方法(继承自RestClientResponseException)不就是你要的吗?

  @ExceptionHandler(value = {HttpClientErrorException.class})
  public ResponseEntity<Object> clientErrorException(HttpClientErrorException ex) {
    return ResponseEntity.status(ex.getStatusCode()).body(ex.getResponseBodyAsString());
  }

或者getResponseBodyAsByteArray() 可能更合适。

【讨论】:

  • 是的。更容易,但我非常感谢你;)。字符串方法实际上是 JSON 可解析的,所以我将继续使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多