0

I am having an issue with the web client.

I am trying to make a post request. The request is good. The thing is, if I add onStatus in order to handle http error codes, I am getting a NPE when calling bodyToMono. If I remove onStatus, I get the response.

we could take this as an example:

Employee createdEmployee = webClient.post()
        .uri("/employees")
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .body(Mono.just(empl), Employee.class)
        .retrieve()
 .onStatus(HttpStatus::isError, clientResponse -> {
          if (clientResponse.statusCode() == HttpStatus.resolve(402)) {
            return Mono.error(new Exception("402"));
          }
          log.error("Error endpoint with status code {}", clientResponse.statusCode());
          if (clientResponse.statusCode() == HttpStatus.resolve(500)) {
            return Mono.error(new Exception("500"));
          }
          if (clientResponse.statusCode() == HttpStatus.resolve(512)) {
            return Mono.error(new Exception("512"));
          }
          return Mono.error(new Exception("Error while processing request"));
        })
        .bodyToMono(Employee.class);

I wan to handle 4xx and 5xx errors including their specific subtypes (404,402) 500, 512

Nesan Mano
  • 1,892
  • 2
  • 26
  • 43
  • Does this answer your question? [Getting the response body in error case with Spring WebClient](https://stackoverflow.com/questions/71643036/getting-the-response-body-in-error-case-with-spring-webclient) – Alex Jan 08 '23 at 03:00
  • bodyToMono give you Mono object, not Employee class. Please stay in the reactor environment if you use Mono or Flux otherwise you will experience an operational anomaly. – Numichi Jan 08 '23 at 08:16

1 Answers1

0

Before bodyToMono() you can use onStatus()

.onStatus(httpStatus -> {
    return httpStatus.is4xxClientError(); // handle 4xx or use .is5xxServerError() or .value()
}, clientResponse -> Mono.error(new RuntimeException("custom exception")))

Another option is to use ExchangeFilterFunction and apply it to your webclient

ExchangeFilterFunction responseErrorHandler =
        ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            clientResponse.statusCode(); // handle any status manually
            return Mono.just(clientResponse);
        });

WebClient webClient = WebClient.builder()
        .filter(responseErrorHandler)
kerbermeister
  • 2,985
  • 3
  • 11
  • 30