🌐
Baeldung
baeldung.com › home › spring › spring webflux › how to get response body when testing the status code in webflux webclient
How to Get Response Body When Testing the Status Code in WebFlux WebClient | Baeldung
June 25, 2024 - In the following examples, we’ll see how we can parse the response body from the REST client WebClient. We’ll link our behavior to the status code returned, and make use of two methods of status code extraction provided by WebClient, onStatus and ExchangeFilterFunction.
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › web › reactive › function › client › WebClient.ResponseSpec.html
WebClient.ResponseSpec (Spring Framework 7.0.9 API)
Return a ResponseEntity with the body decoded to an Object of the given type. For an error response (status code of 4xx or 5xx), the Mono emits a WebClientException. Use onStatus(Predicate, Function) to customize error response handling.
🌐
Jamie Tanna
jvt.me › posts › 2022 › 03 › 04 › spring-webflux-onstatus-body
Accessing the response body with Spring WebFlux `WebClient` with `onStatus` · Jamie Tanna | Software Engineer
March 4, 2022 - 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 { @Test void example() { WebClient webClient = WebClient.builder().build(); webClient .get() .uri("http://localhost:4010/") .retrieve() .onStatus( s -> s.equals(HttpStatus.NOT_FOUND), (e) -> e.bodyToMono(ErrorResponse.class) .handle( (body, handler) -> { LoggerFactory.getLogger(getClass()).warn("HTTP 404 returned: {}", body); handler.error(new BusinessLogicException()); })) .toBodilessEntity() .block(); } private static class BusinessLogicException extends Exception {} private record ErrorResponse(String type, String title, long status, String detail) {} }
People also ask

Should I inject WebClient.Builder or call WebClient.create()?
Inject the builder. Spring Boot pre-configures it with your codecs, ObjectMapper and Actuator metrics; create() produces a client your monitoring cannot see.
🌐
callicoder.com
callicoder.com › home › topics › spring boot › spring webclient and webtestclient tutorial with examples
Spring WebClient and WebTestClient Tutorial with Examples | CalliCoder
Can WebTestClient test a Spring MVC application?
Yes, when it runs against a real port — @SpringBootTest(webEnvironment = RANDOM_PORT) with WebFlux on the test classpath. bindToServer() will also point it at an already-deployed URL.
🌐
callicoder.com
callicoder.com › home › topics › spring boot › spring webclient and webtestclient tutorial with examples
Spring WebClient and WebTestClient Tutorial with Examples | CalliCoder
What is the default request timeout?
There is no response timeout by default. Configure responseTimeout on a Reactor Netty HttpClient and pass it via ReactorClientHttpConnector — without it a hung upstream holds connections until the pool is empty.
🌐
callicoder.com
callicoder.com › home › topics › spring boot › spring webclient and webtestclient tutorial with examples
Spring WebClient and WebTestClient Tutorial with Examples | CalliCoder
🌐
Medium
medium.com › @shivibh › reactive-error-and-response-handling-with-spring-webclient-a-deep-dive-cd476105d885
Reactive Error and Response Handling with Spring WebClient: A Deep Dive | by Shivi Bhardwaj | Medium
October 9, 2024 - Here’s an example: Mono<String> responseMono = webClient.get() .uri("/resource") .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> { // Handle 4xx errors return Mono.error(new RuntimeException("Client Error!")); }) .onStatus(HttpStatus::is5xxServerError, clientResponse -> { // Handle 5xx errors return Mono.error(new RuntimeException("Server Error!")); }) .bodyToMono(String.class) .onErrorResume(e -> { // Fallback logic in case of an error System.out.println("Error occurred: " + e.getMessage()); return Mono.just("Default fallback response"); });
🌐
Getdocs
spring.getdocs.org › en-US › spring-framework-docs › docs › spring-web-reactive › webflux-client › webflux-client-retrieve.html
Untitled :: Spring Docs
By default, responses with 4xx ... as WebClientResponseException.BadRequest, WebClientResponseException.NotFound, and others. You can also use the onStatus method to customize the resulting exception, as the following example shows:...
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
CalliCoder
callicoder.com › home › topics › spring boot › spring webclient and webtestclient tutorial with examples
Spring WebClient and WebTestClient Tutorial with Examples | CalliCoder
November 14, 2017 - retrieve() treats 4xx and 5xx as errors and signals WebClientResponseException. So this, which looks like it handles a missing note: // wrong: a 404 does not produce an empty Mono Mono<Note> maybe = client.get().uri("/notes/{id}", id) .retrieve() .bodyToMono(Note.class); …throws instead. A 404 is a legitimate answer to “does this note exist”, and it needs saying so: public Mono<Note> byIdOrEmpty(long id) { return client.get() .uri("/notes/{id}", id) .retrieve() .onStatus(status -> status == HttpStatus.NOT_FOUND, response -> Mono.empty()) // 404 -> empty, not an error .onStatus(HttpStatusCode::is5xxServerError, response -> response.bodyToMono(String.class) .defaultIfEmpty("") .map(body -> new UpstreamUnavailableException(body))) .bodyToMono(Note.class); }
Find elsewhere
🌐
www.initgrep.com
initgrep.com › posts › java › spring › mastering-spring-webclient:-from-basics-to-advanced-techniques
Mastering Spring WebClient - From Basics to Advanced Techniques | www.initgrep.com
February 4, 2024 - // Sample code for handling errors with WebClient Mono<Order> getOrderDetails(String orderId) { return webClient.get() .uri("/orders/{orderId}", orderId) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> Mono.error(new OrderNotFoundException())) .bodyToMono(Order.class) .onErrorResume(OrderNotFoundException.class, e -> Mono.empty()); } In the above example, we used onErrorResume.
🌐
Medium
medium.com › nerd-for-tech › webclient-error-handling-made-easy-4062dcf58c49
WebClient Error Handling made Easy | by Sudharshan S.R. | Nerd For Tech | Medium
October 20, 2021 - try { String response = webClient.get() .retrieve() .onStatus(httpStatus -> httpStatus.value() == <desired Status code>, error -> Mono.error(new UserDefinedException("error Body"))) .bodyToMono(String.class) .block(); } catch(UserDefinedException userDefinedException) { //exception handling logic } In the above mentioned snippet, we can replace whichever status we want and handle the error accordingly.
🌐
Javadoc.io
javadoc.io › static › org.springframework › spring-webflux › 5.2.1.RELEASE › org › springframework › web › reactive › function › client › WebClient.ResponseSpec.html
WebClient.ResponseSpec (spring-webflux 5.2.1.RELEASE API)
Extract the body to a Flux. By default, if the response has status code 4xx or 5xx, the Flux will contain a WebClientException. This can be overridden with onStatus(Predicate, Function).
🌐
GitHub
github.com › code-with-dilip › spring-webclient › blob › master › employee-app › src › main › java › com › learnwebclient › service › EmployeeRestClient.java
spring-webclient/employee-app/src/main/java/com/learnwebclient/service/EmployeeRestClient.java at master · code-with-dilip/spring-webclient
return webClient.get().uri(EMPLOYEE_BY_ID_V1, employeeId) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> handle4xxErrorResponse(clientResponse)) .onStatus(HttpStatus::is5xxServerError, clientResponse -> handle5xxErrorResponse(clientResponse)) .bodyToMono(Employee.class) .block(); } ·
Author: code-with-dilip
🌐
HowToDoInJava
howtodoinjava.com › home › spring webflux › spring webclient (with hands-on examples)
Spring WebClient (with Hands-On Examples)
September 14, 2023 - import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service public class EmployeeService { private final WebClient webClient; public MyService(WebClient webClient) { this.webClient = webClient; } public Flux<Employee> getAllEmployees() { return webClient.get() .uri("/employees") .retrieve() .onStatus(httpStatus -> !httpStatus.is2xxSuccessful(), clientResponse -> handleErrorResponse(clientResponse.statusCode())) .bodyToFlux(Employee.class) .onErrorResume(Excepti
🌐
GeeksforGeeks
geeksforgeeks.org › advance java › how-to-get-a-response-body-when-testing-the-status-code-in-webflux-webclient
How to Get a Response Body When Testing the Status Code in WebFlux WebClient? - GeeksforGeeks
July 23, 2025 - Reactor is the foundation of WebClient's functional and fluid API, allowing declarative building of asynchronous logic without requiring knowledge of threads or concurrency. It uses the same codecs that are also used to encode and decode request and response material on the server side, and it is completely non-blocking and streaming-compatible. Here is an example of Get a Response Body when Testing the Status Code in WebFlux WebClient.
🌐
Spring
docs.spring.io › spring-framework › reference › web › webflux-webclient › client-retrieve.html
retrieve() :: Spring Framework
By default, 4xx or 5xx responses result in an WebClientResponseException, including sub-classes for specific HTTP status codes. To customize the handling of error responses, use onStatus handlers as follows:
🌐
GitHub
github.com › spring-projects › spring-framework › issues › 20280
Convenience API for custom error handling on WebClient [SPR-15724] · Issue #20280 · spring-projects/spring-framework
July 1, 2017 - Mono<ExampleResponse> exampleResponse = webClient.get() .uri("http://spring.io/example") .exchange() .onStatusCode(HttpStatus.FORBIDDEN, (ClientResponse clientResponse) -> { return new CustomException("Access Forbidden"); }) .on4xx((ClientResponse clientResponse) -> { return new CustomException("Client Error"); }) .on5xx((ClientResponse clientResponse) -> { return new CustomException("Server Error"); }) .flatMap(clientResponse -> clientResponse.bodyToMono(ExampleResponse.class)); Mono<ExampleResponse2> exampleResponse2 = webClient.get() .uri("http://spring.io/example2") .exchange() .onStatusCo
Author: spring-projects
🌐
Stack Overflow
stackoverflow.com › questions › 69411280 › how-to-call-a-method-inside-onstatus-in-spring-webclient
java - How to call a method inside onStatus() in Spring Webclient - Stack Overflow
October 1, 2021 - Currently, I just throw an exception in onStatus() when the response code is 4XX or 5XX. However, I want to call another service ( a compensating transaction to undo the changes) and then throw an Exception. webclient .post() .uri(url, chargeSeqId) ...
🌐
Home
gustavopeiretti.com › home › spring boot how to use web client
Spring Boot - How to use WebClient - Home - Gustavo Peiretti
October 26, 2020 - We can know and manage any http status in our WebClient using the onStatus method. For example, here in case of an error 500 we log in and throw an error using onStatus(…) throwing an exception our ApiWebClientException.
🌐
Medium
medium.com › a-developers-odyssey › spring-web-client-exception-handling-cd93cf05b76
Spring Web Client Exception Handling | by David
October 13, 2021 - On Medium, anyone can share insightful perspectives, useful knowledge, and life wisdom with the world.