How to intercept a response before it is seen by Logbook

1 week ago 17
ARTICLE AD BOX

A question about interceptors. How can I intercept an HTTP response with one interceptor before Logbook intercepts it? The goal is to clean the JSON from unnecessary fields before Logbook intercepts it. That is, the first interceptor removes unnecessary fields and only then passes the cleaned model to Logbook. How can this be implemented? And is it even possible?

I tried writing an interceptor, but when calling execution.execute(request, body), Logbook immediately sees the response and intercepts it before I have a chance to modify anything. What should I do?

I have this configuration:

@Configuration public class ClientConfiguration { @Bean public SomeApiClient apiClient(RestClient.Builder restClientBuilder, Logbook logbook, @Value("${api.external.service.url}") String url, ObjectMapper objectMapper, LogbookRegistry logbookRegistry) { var restClient = restClientBuilder.clone() .baseUrl(url) .requestInterceptor(new CustomJsonInterceptor(objectMapper, logbookRegistry)) .requestInterceptor(new LogbookClientHttpRequestInterceptor(logbook)) .defaultStatusHandler(new CustomHttpErrorHandler()) .build(); RestClientAdapter adapter = RestClientAdapter.create(restClient); HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build(); return factory.createClient(SomeApiClient.class); } }

And here's my interceptor class:

public class CustomJsonInterceptor implements ClientHttpRequestInterceptor { ... @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ClientHttpResponse response = execution.execute(request, body); // This executes the logbook interceptor ... } }
Read Entire Article