Spring Boot 3 RestClient无法捕获TimeoutException及响应处理问题
Spring Boot 3.3.1 RestClient 问题解决方案
问题1:超时异常无法触发onStatus方法
onStatus仅针对**已成功获取HTTP响应但状态码为错误码(4xx/5xx)**的场景生效。而超时(如SocketTimeoutException)属于I/O层异常,此时请求根本没有拿到服务端返回的HTTP响应,因此onStatus不会被触发。
解决方案
通过try-catch捕获ResourceAccessException(超时异常会被包装为该异常),在捕获块中处理超时逻辑:
public String sayHelloFromServer() { try { return restClient.get() .uri("/exception") .retrieve() .onStatus(HttpStatusCode::isError, (request, response) -> { log.error("处理错误状态码: [{}]", response.getStatusCode()); // 可在此添加自定义错误处理逻辑 }) .body(String.class); } catch (ResourceAccessException e) { if (e.getRootCause() instanceof SocketTimeoutException) { log.error("请求超时"); // 自定义超时处理,比如返回默认值或null return null; } // 其他I/O异常按原有逻辑抛出 throw e; } }
问题2:在onStatus中处理错误状态并让body()返回null
onStatus的ErrorHandler默认会抛出WebClientResponseException,若想让后续body()返回null而非抛出异常,推荐使用exchange()方法手动处理响应流程:
解决方案
public String sayHelloFromServer() { try { return restClient.get() .uri("/exception") .exchange((request, response) -> { if (response.getStatusCode().isError()) { log.error("处理错误状态码: [{}]", response.getStatusCode()); // 直接返回null,跳过响应体解析 return Mono.justOrEmpty(null); } // 正常场景解析响应体 return response.bodyToMono(String.class); }) .block(); // 同步场景使用block(),异步场景直接返回Mono即可 } catch (ResourceAccessException e) { // 复用超时异常处理逻辑 if (e.getRootCause() instanceof SocketTimeoutException) { log.error("请求超时"); return null; } throw e; } }
若坚持使用retrieve(),也可通过自定义受检异常实现:
// 自定义异常用于标记HTTP错误状态 static class CustomHttpErrorException extends Exception {} public String sayHelloFromServer() { try { return restClient.get() .uri("/exception") .retrieve() .onStatus(HttpStatusCode::isError, (request, response) -> { log.error("处理错误状态码: [{}]", response.getStatusCode()); throw new CustomHttpErrorException(); }) .body(String.class); } catch (CustomHttpErrorException e) { return null; } catch (ResourceAccessException e) { if (e.getRootCause() instanceof SocketTimeoutException) { log.error("请求超时"); return null; } throw e; } }
内容的提问来源于stack exchange,提问作者Heorhi Utseuski
相关产品推荐
相关产品推荐

