简体   繁体   English

Spring WebClient - 故意返回错误请求

[英]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.如果/user/getData返回错误请求,我希望 WebClient 也返回错误请求。 Instead, WebClient throws an internal server error saying that I've got a bad request.相反,WebClient 抛出一个内部服务器错误,说我有一个错误的请求。

Desired output when executing the WebClient:执行 WebClient 时需要 output:

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

Actual output:实际 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.也许您可以创建一个由异常触发的错误处理程序,然后将 http 错误附加到响应中。 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);
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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