如何在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)); }); }
关键说明
- 替换操作符:用
onErrorResume替代onErrorMap,前者支持返回正常的流元素,而后者仅能转换异常。 - 构建自定义响应:在
onErrorResume的回调中,实例化MagentoAdobeOrderResponse并设置你需要的字段(比如错误码、提示文本)。 - 指定状态码:通过
ResponseEntity.status(...)可以设置响应的HTTP状态码(比如这里的401 Unauthorized),如果不需要特殊状态码,也可以用ResponseEntity.ok(customResponse)。 - 修正语法错误:你原来的代码中
.toEntity(MagentoAdobeOrderResponse.class);后面多了一个分号,这会打断链式调用,需要去掉才能正常编译。
内容的提问来源于stack exchange,提问作者waridc
相关产品推荐
相关产品推荐

