1

So I have a WebClient:

public Mono<UserObject> getData(String id){
    return webClient.get()
        .uri(/user/getData)
        .header("header", header)
        .bodyValue(id)
        .retrieve()
        .bodyToMono(UserObject.class);
}

If /user/getData returns a bad request, I want the WebClient to return a bad request too. Instead, WebClient throws an internal server error saying that I've got a bad request.

Desired output when executing the WebClient:

"status": 400,
"message" : "Bad Request"

Actual output:

"status": 500,
"message" : "org.springframework.web.reactive.function.client.WebClientResponseException$BadRequest: 400 Bad Request from GET .../user/getData"
Jenga
  • 149
  • 4
  • 16

2 Answers2

0

Maybe you can create an error handler which is triggered by the exception and then attach the http error to the response. This answer shows how this can be done.

finisinfinitatis
  • 861
  • 11
  • 23
0

You would need to handle error and return corresponding status

public Mono<UserObject> getData(String id){
    return webClient.post()
            .uri("/user/getData")
            .bodyValue(id)
            .retrieve()
            .bodyToMono(UserObject.class)
            .onErrorResume(e -> {
                if (e instanceof WebClientResponseException) {
                    var responseException = (WebClientResponseException) e;
                    
                    if (responseException.getStatusCode().is4xxClientError()) {
                        return Mono.error(new ResponseStatusException(responseException.getStatusCode()));
                    }
                }
                
                return Mono.error(e);
            });
}
Alex
  • 4,987
  • 1
  • 8
  • 26