首页 > 解决方案 > 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 来自异常?

标签: javaspringrestresponse

解决方案


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

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

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


推荐阅读