【发布时间】: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 或其他东西?
【问题讨论】:
-
也许这就是你要找的答案:baeldung.com/spring-rest-template-error-handling
标签: spring-boot spring-mvc resttemplate