You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 17升级后WebClient onStatus编译错误:HttpStatus::isError适配问题

解决Java17升级后WebClient onStatus方法编译错误

问题原因

升级到Java17时,你应该同步升级了Spring Boot至3.x(对应Spring Framework 6.x)版本。该版本中WebClient.retrieve().onStatus()的第一个参数类型从Predicate<HttpStatus>调整为Predicate<HttpStatusCode>。原代码里的HttpStatus::isError是针对HttpStatus实例的方法引用,无法适配新的HttpStatusCode参数类型,因此触发编译错误。此外原代码的lambda表达式存在语法错误(response ->,多了一个逗号),也会影响编译。

修复步骤

  1. 替换方法引用:将HttpStatus::isError改为HttpStatusCode::isError。HttpStatusCode是Spring 6.x新增的顶层HTTP状态码接口,HttpStatus实现了该接口,且HttpStatusCode本身定义了isError()方法,完全匹配Predicate<HttpStatusCode>的要求。
  2. 修正lambda语法:删除response ->后的多余逗号。

修正后的代码

Mono<AppResponse> bearer = null;
WebClient cl = WebClient.builder()
        .baseUrl(someUrl)
        .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
        .build();
var myUri = cl.post();
var mySpec = myUri.uri(UriBuilder::build);
var keyMap = new LinkedMultiValueMap<>();
keyMap.add("client_sc", cl);
// 省略其他业务代码...
var oneSpec = mySpec.bodyValue(map);

bearer = oneSpec.retrieve()
        .onStatus(HttpStatusCode::isError, response -> 
            response.bodyToMono(String.class).map(e -> {
                log.error("There is Error ", e);
                throw new MyAppException(
                    // 填入你的异常构造参数
                );
            })
        ).bodyToMono(AppResponse.class);
return bearer; 

内容的提问来源于stack exchange,提问作者Jeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:55:09