简体   繁体   中英

Spring WebClient - Purposefully returning bad request

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"

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.

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);
            });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM