Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

It’s often helpful to use the status code from an HTTP response to determine what an application should do next with the given response.

In this tutorial, we’ll look at how to access the status code and response body returned from a REST request using WebFlux’s WebClient.

WebClient was introduced in Spring 5, and can be used for asynchronous I/O while calling RESTful services.

2. Use Case

When making RESTful calls to other services, applications typically use the returned status code to trigger different functionality. Typical use cases include graceful error handling, triggering retries of the request, and determining user error.

As such, when making REST calls, it’s often not enough to get just the response code. Sometimes we want the response body, too.

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.

3. Using onStatus

onStatus is a built-in mechanism that can be used to handle a WebClient response. This allows us to apply finely grained functionality based on specific responses (such as 400, 500, 503, etc.), or on categories of statuses (such as 4XX, and 5XX, etc.):

WebClient
  .builder()
  .build()
  .post()
  .uri("/some-resource")
  .retrieve()
  .onStatus(
    HttpStatus.INTERNAL_SERVER_ERROR::equals,
    response -> response.bodyToMono(String.class).map(Exception::new))

The onStatus method requires two parameters. The first is a predicate that takes in a status code. Execution of the second parameter is based on the output of the first. The second is a function that maps the response to a Mono or an Exception.

In this case, if we see an INTERNAL_SERVER_ERROR (i.e., 500), we’ll take the body, using bodyToMono, and then map that to a new Exception.

We can chain onStatus calls to be able to provide functionality for different status conditions:

Mono<String> response = WebClient
  .builder()
  .build()
  .post()
  .uri("some-resource")
  .retrieve()
  .onStatus( 
    HttpStatus.INTERNAL_SERVER_ERROR::equals,
    response -> response.bodyToMono(String.class).map(CustomServerErrorException::new)) 
  .onStatus(
    HttpStatus.BAD_REQUEST::equals,
    response -> response.bodyToMono(String.class).map(CustomBadRequestException::new))
  ... 
  .bodyToMono(String.class);

// do something with response

Now onStatus calls map to our custom exceptions. We defined exception types for each of the two error statuses. The onStatus method allows us to use any type we choose.

4. Using ExchangeFilterFunction

An ExchangeFilterFunction is another way to handle specific status codes and get response bodies. Unlike onStatus, the exchange filter is flexible, and applies to filter functionality based on any boolean expression.

We can benefit from the flexibility of an ExchangeFilterFunction to cover the same categories as the onStatus function.

First, we’ll define a method to handle the returned logic based on the status code given a ClientResponse:

private static Mono<ClientResponse> exchangeFilterResponseProcessor(ClientResponse response) {
    HttpStatusCode status = response.statusCode();
    if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
        return response.bodyToMono(String.class)
          .flatMap(body -> Mono.error(new CustomServerErrorException(body)));
    }
    if (HttpStatus.BAD_REQUEST.equals(status)) {
        return response.bodyToMono(String.class)
          .flatMap(body -> Mono.error(new CustomBadRequestException(body)));
    }
    return Mono.just(response);
}

Next, we’ll define the filter and use a method reference to our handler:

ExchangeFilterFunction errorResponseFilter = ExchangeFilterFunction
  .ofResponseProcessor(WebClientStatusCodeHandler::exchangeFilterResponseProcessor);

Similar to the onStatus calls, we’re mapping to our Exception types on error. However, using Mono.error will wrap this Exception in a ReactiveException. This nesting should be kept in mind when handling the error.

Now we’ll apply this to an instance of a WebClient to achieve the same effect as the onStatus chained call:

Mono<String> response = WebClient
  .builder()
  .filter(errorResponseFilter)
  .build()
  .post()
  .uri("some-resource")
  .retrieve()
  .bodyToMono(String.class);

// do something with response

5. Conclusion

In this article, we covered a couple of the methods to get the response body based on the HTTP status header. Based on the status code, the onStatus method allows us to plug specific functionality. In addition, we can use the filter method to plug in a general-purpose method to handle post-processing on all responses.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

2 Comments
Oldest
Newest