首页 > 解决方案 > 在微服务响应失败的情况下提取Web客户端响应,http状态码为4XX

问题描述

我对春天有点陌生。我开始使用 Web 客户端转换我的其余模板调用之一。我遇到了一些问题。我的代码如下

public Mono<TestDateResponse> getTestDate() {
        WebClient.RequestBodyUriSpec requestBodyUriSpec = webClient.post();
        WebClient.RequestBodySpec requestBodySpec =
                requestBodyUriSpec.header(ApplicationConstants.HTTP_AUTH_TOKEN, "xyz");
        requestBodyUriSpec.uri(dateLookupServiceEndPoint);

        requestBodySpec.bodyValue(request);
        WebClient.ResponseSpec response = requestBodySpec.retrieve().onStatus(HttpStatus::is4xxClientError, clientResponse -> {
            return clientResponse.bodyToMono(ErrorResponse.class)
                    .flatMap(body -> {
                        log.info("Body is: {}", body);
                        return Mono.error(new ServiceException(body.getErrorMessage(), clientResponse.rawStatusCode()));
                    });
        });
        response
                .toBodilessEntity()
                .timeout(Duration.ofSeconds(5))
                .retryWhen(
                        Retry.fixedDelay(maxRetryAttempts, Duration.ofMillis(fixedDelay))
                                .onRetryExhaustedThrow((spec, rs) -> rs.failure()));
                return response.bodyToMono(TestDateResponse.class);
    }

我正在尝试捕获如下响应。

try {
    accountOpenDateRes = accountOpenDateMonoResponse.block(timeout);
    } catch(Exception e) {
        log.info("Exception in date lookup");
    }

只要我的 datelookupservice 返回 TestDateResponse.class 的状态码为 200 的响应,此方法就可以正常工作。我正在寻找一种在 http 状态为 400 的情况下捕获响应的方法,其中我的响应是 ErrorResponse.class。和上面的代码导致不同的excpetion如下

SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is reactor.core.Exceptions$ReactiveException: java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 5000ms in 'flatMap' (and no fallback has been configured)] with root cause
java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 5000ms in 'flatMap' (and no fallback has been configured)
    at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.handleTimeout(FluxTimeout.java:294)

似乎我无法弄清楚 onStatus 的用法。有什么建议么?。谢谢

标签: springspring-bootspring-webfluxspring-webclient

解决方案


推荐阅读