Spring REST 响应中的 RestClientResponseException 缺少响应 body

Missing response body from RestClientResponseException in Spring REST response

在我的 Spring 启动 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
}

如果我用邮递员 调用我的端点 ,如果发生异常,我会收到此响应,这很完美:

{
    "name": "INTERNAL",
    "status": 500,
    "message": "something happened",
}

但是当我在我的应用程序中调用端点时,我捕获了RestClientResponseException(基本上是HttpClientErrorException),我可以在异常中看到原来是 500,但是没有 body,它是空的。

我在应用程序中是这样称呼它的:

try {
    ResponseEntity<WhateverObject> entity = restTemplate.exchange(url, HttpMethod.POST, getBaseHeadersAsHttpEntity(), WhateverObject.class);
    //...
} catch (RestClientResponseException e) {
    //... ErrorObject of exception is missing here
}

如何在异常的情况下得到相同的body,所以我自己的ErrorObject从异常中得到?

感谢@Hemant Patel 的评论,在尝试设置一个新的 ErrorHandler 之后,我发现我唯一需要设置的是一个新的请求工厂:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

并且这个工厂能够在后台成功设置响应体。