如何在webclient reactor中添加或忽略特定的http状态代码?

zbdgwd5y  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(359)

我使用此方法管理项目的所有请求:

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

但是当响应正常但有特殊条件时,我使用状态代码为432的响应的api之一,我必须显示它,但webclient显示此错误:

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....

我怎样才能避免这种情况和正常的React?是否可以将此状态代码添加到我的jsonnode.class或Map响应和状态代码的自定义泛型类或任何想法?谢谢

ogsagwnx

ogsagwnx1#

从java文档(这也适用于 onRawStatus 方法)

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.

示例代码片段如下所示

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

相关问题