为什么 Spring Webclient onStatus 不适用于 HttpStatus::is4xxClientError?

zim*_*mtz 2 spring undefined http-error spring-webflux spring-webclient

我已经基于该spring-boot-starter-webflux工件实现了一个网络客户端。

\n

代码:

\n
// create  client bean to use throughout services\n@Bean\npublic WebClient geoserverWebClient() {\n    // to not fall prone to DataBufferLimitException\n    final int size = 16 * 1024 * 1024;\n    final ExchangeStrategies s\xce\xa9trategies = ExchangeStrategies.builder()\n        .codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size))\n        .build();\n    \n    return WebClient.builder()\n        .exchangeStrategies(strategies)\n        .baseUrl(geoserverURL) \n        .defaultHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(geoserverBasicAuth.getBytes()))\n        .build();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

到目前为止,我在使用它时没有遇到任何问题,例如:

\n
// send getMap WMS to geoserver\npublic Mono<byte[]> getMap(String requestURL){\n\n    return geoserverWebClient\n    .get()\n    .uri(requestURL)\n    .retrieve()\n    .bodyToMono(byte[].class);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是,如果我onStatus向其中添加该方法以检查 HTTP 错误,则会收到错误:“WebClient.ResponseSpec 类型中的方法 onStatus(Predicate, Function<ClientResponse,Mono<? extends Throwable>>) 不适用于参数 (HttpStatus::is4xxClientError" foronStatus"The type HttpStatus does not Define is4xxClientError(HttpStatusCode)" forHttpStatus

\n
// various other imports ...\n\nimport org.springframework.http.HttpStatus;\n\n// send getMap WMS to geoserver\npublic Mono<byte[]> getMap(String requestURL){\n\n    return geoserverWebClient\n    .get()\n    .uri(requestURL)\n    .retrieve()\n    .onStatus(HttpStatus::is4xxClientError,\n            error -> Mono.error(new RuntimeException("API not found")))\n    .bodyToMono(byte[].class);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我已经阅读了该方法,并且由于我使用的是 Spring Boot 版本 3.0.5,所以我不明白为什么它不能按照记录的方式工作。

\n

我尝试从 the 开始,Builder但它不会改变一点。我还尝试了其他 HTTP 错误,甚至写出了org.springframework.http.HttpStatus::is4xxClientError. 这些都不起作用。我唯一没有做的就是实例化一个HttpStatus对象 - 但我假设该.onStatus()方法将从该方法中获取正确的对象.retrieve()

\n

我认为我的 IDE 目前可能无法正确加载导入。我已经关闭了该项目,重新启动了 IDE,然后重新打开了该项目,但没有效果。即使删除本地 .m2 文件夹也无法解决问题。

\n

这是 Java/Spring 问题还是我的 IDE(VS Code)问题?

\n

小智 9

Predicate 中的类型参数( 的第一个参数onStatus(...))不是 类型org.springframework.http.HttpStatus,而是类型org.springframework.http.HttpStatusCode(恰好是HttpStatus枚举实现的接口)。

因此,将方法引用从 切换HttpStatus::is4xxClientErrorHttpStatusCode::is4xxClientError,错误就会消失。