登录
首页 >  文章 >  java教程

WebClient异常处理及自定义返回方法

时间:2026-01-25 10:00:53 287浏览 收藏

有志者,事竟成!如果你在学习文章,那么本文《WebClient 异常处理与自定义响应返回》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

如何在 WebClient 异常时返回自定义 ResponseEntity?

本文介绍在 Spring WebFlux 中使用 WebClient 调用远程接口时,当发生如 401 Unauthorized 等特定异常,如何优雅地捕获并统一返回符合业务规范的 `ResponseEntity`,而非抛出原始异常或仅封装错误对象。

在响应式编程中,WebClient 默认将 HTTP 错误状态(如 401、403、500)封装为 WebClientResponseException 及其子类(如 WebClientResponseException.Unauthorized),并不会自动触发 Spring MVC 的异常处理机制——因为 WebClient 运行在服务调用方(客户端)逻辑中,而非控制器层。因此,直接在链式调用中使用 .onErrorMap() 无法返回 ResponseEntity,原因在于:

  • onErrorMap 仅用于转换异常类型(返回新异常),不能生成 Mono>;
  • toEntity(Class) 返回的是 Mono>,但一旦发生错误,整个 Mono 就会以错误终止,需显式恢复(recover)才能继续流式返回。

✅ 正确做法是:结合 onStatus + onErrorResume 实现声明式错误响应构造,避免依赖 @ControllerAdvice(该方案适用于 被调用方 的 Controller 异常处理,不适用于 WebClient 调用方的响应定制)。

✅ 推荐方案:在 WebClient 链路中内聚处理异常响应

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()
        // 拦截特定状态码(如 401),转为自定义错误响应
        .onStatus(HttpStatus::is4xxClientError,
            response -> {
                if (response.statusCode().equals(HttpStatus.UNAUTHORIZED)) {
                    MagentoAdobeOrderResponse errorBody = new MagentoAdobeOrderResponse();
                    // 可在此设置错误字段,如 code="UNAUTHORIZED", message="Token expired"
                    return Mono.just(new WebClientResponseException.Unauthorized(
                        "Unauthorized", null, null, new byte[0], Charset.defaultCharset()));
                }
                return Mono.empty();
            })
        // 将 WebClientResponseException 映射为 ResponseEntity
        .toEntity(MagentoAdobeOrderResponse.class)
        .onErrorResume(WebClientResponseException.class, ex -> {
            HttpStatus status = ex.getStatusCode();
            MagentoAdobeOrderResponse fallback = buildErrorResponse(ex); // 自定义错误体构建逻辑
            return Mono.just(ResponseEntity.status(status).body(fallback));
        });
}

其中 buildErrorResponse() 示例:

private MagentoAdobeOrderResponse buildErrorResponse(WebClientResponseException ex) {
    MagentoAdobeOrderResponse resp = new MagentoAdobeOrderResponse();
    resp.setCode(String.valueOf(ex.getRawStatusCode()));
    resp.setMessage(ex.getStatusText());
    resp.setTimestamp(Instant.now());
    // 可选:解析原始响应体中的错误详情(若服务端返回 JSON 错误结构)
    try {
        JsonNode errorNode = new ObjectMapper().readTree(ex.getResponseBodyAsString());
        resp.setDetails(errorNode.toString());
    } catch (Exception ignored) {}
    return resp;
}

⚠️ 注意事项

  • ❌ 不要滥用 @ControllerAdvice 处理 WebClient 异常:它只对 @RestController 抛出的异常生效,对 WebClient 内部异常无感知;
  • ✅ onStatus 是拦截非 2xx 响应的首选方式,比 onErrorMap 更精准(后者仅捕获已抛出的异常);
  • ✅ 使用 onErrorResume 替代 onErrorMap 来实现“错误 → 新 Mono”的转换,从而返回 ResponseEntity;
  • ? 若需全局复用该逻辑,可封装为 WebClient 的 ExchangeFilterFunction,实现跨服务调用的一致错误响应策略。

✅ 总结

返回自定义 ResponseEntity 的核心在于:在响应式流中主动拦截错误状态,并通过 onErrorResume 恢复为合法的 Mono>。这种方式保持了响应式链的完整性,无需侵入控制器层,也避免了异常传播带来的不可控性,是 WebClient 场景下最推荐、最可控的实践方案。

本篇关于《WebClient异常处理及自定义返回方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>