Search code examples
javaspringspring-webfluxspring-webclient

How add or Ignoring a specific http status code in WebClient reactor?


I have a this method that manage all request of my project:

 private Mono<JsonNode> postInternal(String service, String codPayment, String docNumber, RequestHeadersSpec<?> requestWeb) {

    return requestWeb.retrieve().onStatus(HttpStatus::is4xxClientError,
            clientResponse -> clientResponse.bodyToMono(ErrorClient.class).flatMap(
                    errorClient -> clientError(service, codPayment, clientResponse.statusCode(), docNumber, errorClient)))
            .onStatus(HttpStatus::is5xxServerError,
                    clientResponse -> clientResponse.bodyToMono(ErrorClient.class)
                            .flatMap(errorClient -> serverError(service, codPayment, docNumber, errorClient)))
            .onRawStatus(value -> value > 504 && value < 600,
                    clientResponse -> clientResponse.bodyToMono(ErrorClient.class)
                            .flatMap(errorClient -> otherError(service, codPayment, docNumber, errorClient)))
            .bodyToMono(JsonNode.class);
}

But one of the API that i consume response with Status code 432 when the response is ok but have a special condition in it and i must show it but webClient show this error:

org.springframework.web.reactive.function.client.UnknownHttpStatusCodeException: Unknown status code [432]
at org.springframework.web.reactive.function.client.DefaultClientResponse.lambda$createException$1(DefaultClientResponse.java:220) ~[spring-webflux-5.2.1.RELEASE.jar:5.2.1.RELEASE]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
|_ checkpoint ⇢ 432 from POST https://apiThatIConnectTo....

How can i avoid this and response normally? and is possible to add this status code to my JsonNode.class or a custom generic class that map the response and the status code or any ideas? thanks


Solution

  • From the java doc. (This also applies to the onRawStatus method)

    To suppress the treatment of a status code as an error and process it as a normal response, return Mono.empty() from the function. The response will then propagate downstream to be processed.
    

    An example code snippet would look like

        webClient.get()
                .uri("http://someHost/somePath")
                .retrieve()
                .onRawStatus(status -> status == 432, response -> Mono.empty())
                .bodyToMono(String.class);