【问题标题】:Missing response body from RestClientResponseException in Spring REST responseSpring REST 响应中缺少来自 RestClientResponseException 的响应正文
【发布时间】:2018-05-15 13:07:17
【问题描述】:

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

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

{
    "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 从异常中获取?

【问题讨论】:

  • 如果您在应用程序中使用RestTemplate 调用端点,您需要在其中覆盖 DefaultErrorHandler。
  • 感谢您的有用评论。试了一下,发现后台无法存储响应体,发现需要设置新的请求工厂:restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

标签: java spring rest response


【解决方案1】:

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

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多