spring boot 全局异常处理可以通过实现 handlerexceptionresolver 接口或配置 @controlleradvice 来捕获拦截器抛出的异常。关键在于确保拦截器中抛出的异常未被内部 try-catch 吞掉,而是直接向上抛出,这样 spring mvc 的异常解析链才能将其拦截并交由全局处理器统一处理。

如何配置全局异常处理器以拦截自定义异常
通过定义一个带有 @ControllerAdvice 注解的类,并在其中使用 @ExceptionHandler 方法指定要处理的异常类型,即可实现对特定异常的集中拦截。当拦截器抛出该异常时,Spring 会自动调用对应的方法返回响应。

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomAuthException.class)
public ResponseEntity<string> handleCustomAuthException(CustomAuthException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ex.getMessage());
}
}</string>
上述代码定义了一个全局异常处理器,专门处理 CustomAuthException。当拦截器抛出此异常时,将返回 401 状态码及错误信息。
拦截器中异常抛出与全局处理的交互流程
在拦截器的 preHandle 或 postHandle 方法中,若检测到非法请求(如缺少 Token),应直接抛出异常,而不是返回 false 或打印日志。这样异常会沿着 Spring MVC 的执行链向上传递,最终被 @ControllerAdvice 捕获。

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token == null || !token.startsWith("Bearer ")) {
throw new CustomAuthException("Missing or invalid token");
}
return true;
}
}
该拦截器在 preHandle 中检查 Authorization 头,若不符合要求则抛出 CustomAuthException,从而触发全局异常处理逻辑。
当拦截器抛出未声明异常时全局处理器能否捕获
只要异常是 RuntimeException 的子类且未被拦截器内部 catch 住,全局异常处理器就能捕获。即使拦截器方法签名未声明 throws,运行时抛出的非受检异常仍会被 Spring MVC 异常解析机制捕获。











