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

WebClient.onStatus中按HttpStatus返回错误信息遇response.rawStatusCode失效问题

问题解决:WebClient按HttpStatus分支抛异常失败

你的代码存在两个核心问题,导致response.rawStatusCode()无法正常工作:

1. 语法错误导致代码编译失败

onStatus方法调用缺少闭合括号,使得bodyToMono被错误绑定到switch语句的返回值上,而非WebClient的请求调用链。

2. rawStatusCode()存在空指针风险

response.rawStatusCode()返回Integer类型,当响应状态码无法解析为标准HttpStatus时可能返回null,引发空指针异常。更稳妥的方式是通过response.statusCode().value()获取状态码,借助HttpStatus对象避免null值问题。

修正后的代码

JsonNode APISong = webClient.get()
        .uri("/catalog/" + this.storefront + "/songs/" + id)
        .retrieve()
        .onStatus(HttpStatus::isError, response -> {
            int statusCode = response.statusCode().value();
            return switch (statusCode) {
                case 401 -> Mono.error(new RuntimeException("Unauthorized Apple Music API call"));
                case 500 -> Mono.error(new RuntimeException("Internal Server Error (Apple Music API call)"));
                default -> Mono.error(new RuntimeException("Something went wrong during Apple Music API call"));
            };
        })
        .bodyToMono(JsonNode.class)
        .block();

额外优化建议

  • 避免使用通用Exception,改用RuntimeException或自定义业务异常类,符合Spring WebFlux的异常处理规范
  • 可将状态码与异常信息的映射逻辑抽取为单独方法,进一步提升代码可读性
  • 如需处理更多状态码(如404、403),直接在switch中添加对应case分支即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:37:11