spring boot 全局异常处理捕获节点下线异常的核心做法是注册一个自定义的 clienthttprequestinterceptor,在拦截器中检查响应状态码是否为 404 not found 或 503 service unavailable,并据此抛出特定的业务异常(如 nodeofflineexception),随后在全局异常处理器 @restcontrolleradvice 中统一捕获该异常并返回友好的错误提示。这样做可以将底层的 http 通信细节与业务逻辑解耦,确保当服务节点不可用时,系统能立即感知并做出相应处理。

如何配置拦截器以识别节点下线状态
要识别节点下线,需要在创建 RestTemplate 时注入拦截器。拦截器的 intercept 方法会接收请求、执行实际调用并获取响应。如果响应状态码为 404 或 503,通常意味着目标节点已停止服务或拒绝连接,此时应中断流程并抛出异常。通过这种方式,我们可以将网络层面的失败转化为应用层面的信号。

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Arrays;
public class NodeDownInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
// 假设 404 或 503 代表节点下线
if (response.getStatusCode().value() == 404 || response.getStatusCode().value() == 503) {
throw new NodeOfflineException("Target node is offline or unavailable");
}
return response;
}
}
// 配置 RestTemplate
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Arrays.asList(new NodeDownInterceptor()));
全局异常处理器如何统一响应节点下线错误
定义好自定义异常后,需要创建一个带有 @RestControllerAdvice 注解的类来捕获它。在该类中编写一个使用 @ExceptionHandler(NodeOfflineException.class) 的方法,该方法接收异常对象并返回一个标准化的 JSON 响应结构。这样,无论哪个 Controller 触发了节点下线异常,都会由这个统一的入口进行处理,保证前端收到一致的错误格式。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NodeOfflineException.class)
public ResponseEntity<string> handleNodeOffline(NodeOfflineException ex) {
// 返回具体的错误信息或日志记录
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body("Service temporarily unavailable: " + ex.getMessage());
}
}</string>
当节点下线时全局异常处理的具体返回结果是什么
当程序运行过程中触发节点下线条件时,全局异常处理器的 handleNodeOffline 方法会被调用。最终返回给客户端的是一个 HTTP 状态码为 503 Service Unavailable 的响应,其 Body 内容为字符串形式的错误描述,例如 "Service temporarily unavailable: Target node is offline or unavailable"。这种处理方式确保了上层业务代码不需要在每个调用处都进行 try-catch 判断,而是由基础设施层统一接管。











