Spring Boot RestTemplate ClientHttpRequestInterceptor日志响应主体,如果发生异常

时间:2020-02-11 15:33:54

标签: java spring spring-boot resttemplate interceptor

我正在使用ClientHttpRequestInterceptor报告RestTemplate的请求和响应。如果发生异常,我需要记录响应,比如说模板是否尝试使用错误的类来分解响应。

启用拦截器的方法如下:

@Bean
public RestTemplate restTemplate(ReportingConfiguration reportingConfiguration) {
    return new RestTemplateBuilder()
            .interceptors(new RestTemplateInterceptor())
            .build();
}

此处唯一接受的接口是ClientHttpRequestInterceptor。 拦截器看起来像:

@Override
public ClientHttpResponse intercept(HttpRequest req, byte[] body, ClientHttpRequestExecution execution) throws IOException {

    ...

    ClientHttpResponse response = null;
    try {
        response = execution.execute(request, body);
    } catch (Exception e) {
        System.out.println("I need to get the response here");
    }

    ...

我知道在这堂课上不可能得到答复,您能给个替代解决方案吗?

这是该异常的一个示例:(请不要解释如何摆脱此异常,我知道我为什么得到这个,我只是想记录有效载荷,以防发生这种情况)

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "items" (class com.exapmle.group.web.beans.Response), not marked as ignorable (3 known properties: "text", "status", "set-cookies"]) at [Source: (ByteArrayInputStream); line: 1, column: 11] (through reference chain: com.exapmle.group.web.beans.Response["items"]) at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61) at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823) at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)

1 个答案:

答案 0 :(得分:-2)

这应该有效:

ClientHttpResponse response = null;
try {
    response = execution.execute(request, body);
} catch (Exception e) {
    System.out.println("I need to get the response here", e.getMessage());
}
相关问题