How can I get webflux response body twice? Store some data from request/response

Viewed 8

I created a filter to log some important data from the request and response...

@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
    URI uri = request.url();
    HttpMethod method = request.method();

    return next.exchange(request).onErrorResume(err -> {
        writeToFile(method, uri, 500, "", true);

        return Mono.error(err);
    }).flatMap((response) -> {
        return response.bodyToMono(String.class).flatMap(body -> {
            writeToFile(method, uri, response.rawStatusCode(), body, false);

            return Mono.just(response);
        });
    });
}

The idea of this filter is to register some data and let the rest work exactly the same.

Expected: This was my attempt to keep the rest of the code untouched and just include a filter to store some data apart from the normal flow.
Actual: It works, except when the real code calls bodyToMono, it returns null

At some point of the normal flow, I am doing something similar to this:

return client.get().uri(...).exchangeToMono((response) -> {
    return response.bodyToMono(MyObject.class);
})

It works flawlessly when I remove the filter.

So I discovered I can't call bodyToMono twice the way I am using probably because the first call is consuming the body and then it is empty in the second call.

0 Answers
Related