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

如何在Java WebClient捕获特定异常时返回自定义实体响应?

实现WebClient异常时返回自定义ResponseEntity的方案

当然可以实现你的需求!你当前用的onErrorMap操作符是用来转换异常类型的,它只能抛出另一个异常实例,没法直接返回正常的响应实体。要达成“捕获特定异常后返回自定义ResponseEntity<MagentoAdobeOrderResponse>”的目标,你需要改用onErrorResume操作符——它允许在捕获到指定异常时,返回一个替代的Mono流,也就是你想要的自定义响应。

修改后的完整代码

public Mono<ResponseEntity<MagentoAdobeOrderResponse>> getOrder(String orderId, String token){
    return webClient.get()
            .uri(orderUrl + "/" + orderId)
            .header(HttpHeaders.CACHE_CONTROL, "no-cache")
            .header(HttpHeaders.ACCEPT, "*/*")
            .header(HttpHeaders.ACCEPT_ENCODING, "deflate, br")
            .header(HttpHeaders.CONNECTION, "keep-alive")
            .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
            .retrieve()
            .toEntity(MagentoAdobeOrderResponse.class)
            // 替换onErrorMap为onErrorResume,返回自定义响应
            .onErrorResume(Unauthorized.class, ex -> {
                // 构建你的自定义响应实体
                MagentoAdobeOrderResponse customResponse = new MagentoAdobeOrderResponse();
                // 根据需求设置响应体的字段,比如错误码、提示信息
                customResponse.setErrorCode(String.valueOf(HttpStatus.UNAUTHORIZED.value()));
                customResponse.setErrorMessage(ButttonMilesConstants.BANK_PROBLEMS_ERROR_MESSAGE);
                
                // 包装成ResponseEntity,可指定HTTP状态码
                return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(customResponse));
            });
}

关键说明

  1. 替换操作符:用onErrorResume替代onErrorMap,前者支持返回正常的流元素,而后者仅能转换异常。
  2. 构建自定义响应:在onErrorResume的回调中,实例化MagentoAdobeOrderResponse并设置你需要的字段(比如错误码、提示文本)。
  3. 指定状态码:通过ResponseEntity.status(...)可以设置响应的HTTP状态码(比如这里的401 Unauthorized),如果不需要特殊状态码,也可以用ResponseEntity.ok(customResponse)。
  4. 修正语法错误:你原来的代码中.toEntity(MagentoAdobeOrderResponse.class);后面多了一个分号,这会打断链式调用,需要去掉才能正常编译。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:50:36