spring boot 全局异常处理无法直接捕获 consul 健康检查失败产生的异常,因为健康检查是服务端主动发起的 http 请求,其响应由 spring mvc 的 dispatcherservlet 直接返回,不经过业务层的异常处理器。要捕获并处理这些异常,需要在 controller 层使用 @exceptionhandler 注解定义专门的方法,或者在 webmvcconfigurer 中注册自定义的 handlerexceptionresolver。

如何拦截 Consul 健康检查请求中的特定错误
通过实现 HandlerExceptionResolver 接口,可以拦截所有未处理的异常,包括健康检查端点抛出的异常。这种方式比在每个 Controller 中添加 @ExceptionHandler 更灵活,适合统一处理跨模块的健康检查逻辑。

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ConsulHealthExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (request.getRequestURI().contains("/health")) {
try {
response.setStatus(503);
response.getWriter().write("Consul Health Check Failed: " + ex.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView();
}
return null;
}
}
如何在 Controller 中针对健康检查抛出特定异常
在 Controller 方法中,可以通过 @ExceptionHandler 捕获特定类型的异常,并在健康检查端点中手动抛出这些异常。这样可以确保只有健康检查相关的异常被特殊处理,而其他业务异常不受影响。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class HealthController {
@GetMapping("/health")
public String healthCheck() throws Exception {
// 模拟健康检查逻辑
throw new RuntimeException("Service Unavailable");
}
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException(RuntimeException ex) {
return "Error: " + ex.getMessage();
}
}
基于 Consul 健康检查返回 503 状态码的具体问题
当 Consul 健康检查返回 503 状态码时,表示服务不可用。这通常是因为健康检查端点抛出了异常,导致 Spring MVC 无法返回正常的 200 状态码。通过上述两种方法,可以确保在健康检查失败时,返回明确的错误信息,而不是默认的 404 或 500 状态码。


















