java - Spring REST 响应中缺少来自 RestClientResponseException 的响应正文
问题描述
在我的Spring Boot REST 应用程序中,我有一个端点,我在其中做一些事情。我还有一个@Provider
,我可以在其中捕获和映射过程中发生的所有异常:
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable ex) {
ErrorObject error = new ErrorObject("INTERNAL", 500, ex.getMessage());
return Response.status(error.getStatus()).entity(error).type(MediaType.APPLICATION_JSON).build();
}
}
这ErrorObject
只是一个带有一些信息的基本 pojo:
public class ErrorObject implements Serializable {
private static final long serialVersionUID = 4181809471936547469L;
public ErrorObject(String name, int status, String message) {
this.name = name;
this.status = status;
this.message = message;
}
private String name;
private int status;
private String message;
setters/getters
}
如果我用 postman调用我的端点,如果发生异常,我会得到这个响应,这是完美的:
{
"name": "INTERNAL",
"status": 500,
"message": "something happened",
}
但是当我在我的应用程序中调用端点时,我捕获了RestClientResponseException
(基本上是HttpClientErrorException
),我可以在异常中看到它是 500,但是没有正文,它是空的。
这就是我在我的应用程序中调用它的方式:
try {
ResponseEntity<WhateverObject> entity = restTemplate.exchange(url, HttpMethod.POST, getBaseHeadersAsHttpEntity(), WhateverObject.class);
//...
} catch (RestClientResponseException e) {
//... ErrorObject of exception is missing here
}
如果出现异常,我怎样才能获得相同的主体,所以我自己的 ErrorObject 来自异常?
解决方案
感谢@Hemant Patel 的评论,在尝试设置一个新的ErrorHandler 之后,我发现我唯一需要设置的是一个新的请求工厂:
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
并且这个工厂能够成功地在后台设置响应体。
推荐阅读
- .net-core - 将 Scaffold-DbContext 与用户机密一起使用
- python - cv2 API 中已弃用的 CreateImage 函数的替代方案
- python - 警报框问题总是返回响应 == 0
- mule - HTTP 基本身份验证策略未反映到 mule 3 中的特定方法和资源
- javascript - 如何将 JSON 数据从 API 映射到 div
- django - 禁用使用 Django 登录 gunicorn 以获取特定请求/URL/端点
- uefi - 如何删除 UEFI 认证变量?
- r - Keras k_pool2d 后端函数引发类型错误
- c# - 为什么我的 Listview 多次显示相同的值?
- python - 熊猫:read_json urllib.error.URLError:
, 用于工作的代码