Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle HTTP status code in Spring Webclient

I'm stuck trying to do simple error handling when calling a remote service. The service returns a Map. The behaviour I'm looking for is:

  • HTTP 200 --> Return body (Map<String, String>).
  • HTTP 500 --> Throw a particular exception
  • HTTP 404 --> Simply return Null.

Here's my code:

private Map<String, String> loadTranslations(String languageTag) {
    try {
        WebClient webClient = WebClient.create(serviceUrl);
        Map<String, String> result = webClient.get()
            .uri("/translations/{language}", languageTag)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),
                clientResponse -> Mono.error(new MyServiceException(HttpStatus.NOT_FOUND)))
            .onStatus(HttpStatus::is5xxServerError, response -> Mono.error(new MyServiceException(response.statusCode())))
            .bodyToMono(Map.class)
            .block();

        return result;
    } catch (MyServiceException ex) {  // doesn't work as in reality it throws ReactiveException
        ....
    }
}

I don't know how to have the result of block() return NULL (or something that I can interpret as "404 was received"). The idea would be to just return NULL on 404 and throw an exception on 500.

I tried returning Mono.empty() but in that case the result variable contains the body of the response as Dictionary (I'm using standard Spring error bodies that contain timestamp, path, message).

What I'm doing wrong?

Thank you,

like image 430
tggm Avatar asked Aug 11 '26 16:08

tggm


1 Answers

ResponseSpec class's onStatus method signature from Spring WebFlux 5.x

ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate,
                Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction);

changed to

ResponseSpec onStatus(Predicate<HttpStatusCode> statusPredicate,
                Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction);

in Spring Web 6.x

May be while upgrading to JDK 17 you upgraded spring version as well.

So change HttpStatus::isError to HttpStatusCode::isError and the error should go away.

like image 82
krishnakumarp Avatar answered Aug 14 '26 12:08

krishnakumarp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!