Commit ea7be47a authored by Jamie Tanna's avatar Jamie Tanna
Browse files

Blogument `onStatus` response body interactions

Closes #1175.
parent f1942b97
Pipeline #484821890 passed with stages
in 6 minutes and 11 seconds
title: "Accessing the response body with Spring WebFlux `WebClient` with `onStatus`"
description: "How to access the body of an (error) response when using `WebClient`'s `onStatus` method."
- blogumentation
- spring
- spring-boot
- java
license_code: Apache-2.0
license_prose: CC-BY-NC-SA-4.0
date: 2022-03-04T16:55:25+0000
slug: spring-webflux-onstatus-body
- ""
While [writing some integration tests for a `WebClient`]( today, I wanted to take advantage of the `onStatus` method to perform some operational logging using the response body, _before_ I mapped it to a particular exception.
I found it really quite difficult to do, as I wanted to use `.block()`, but found it didn't work, and other means I'd tried just ended up not executing.
I found that the following ended up working:
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClient;
class Example {
void example() {
WebClient webClient = WebClient.builder().build();
s -> s.equals(HttpStatus.NOT_FOUND),
(e) ->
(body, handler) -> {
LoggerFactory.getLogger(getClass()).warn("HTTP 404 returned: {}", body);
handler.error(new BusinessLogicException());
private static class BusinessLogicException extends Exception {}
private record ErrorResponse(String type, String title, long status, String detail) {}
This use of `handle` allows it to process asynchronously, giving us the chance to interact with the parsed response body.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment