
























在 Spring Boot 中我们常用 @RestControllerAdvice 和 @ControllerAdvice 来全局捕获异常来优雅的处理异常,但并不是真的能捕获全部异常,我遇到的一次情况是:自定义过滤器继承 OncePerRequestFilter,在过滤器中会交验 Token,当 Token 过期后会抛出一个 ExpiredJwtException 异常,但无法被捕获。问题其实就出在了 Filter 中抛出的异常,我们来看下 Spring Boot 对过滤器、拦截器和 Controller 的执行顺序。Spring Boot Filter过滤器、Interceptor拦截器和 ControllerAdvice 的执行顺序在一个请求进来以后,会以如下的顺序进行执行和传递:
总的来说,拦截方式的执行顺序是过滤器->拦截器->ControllerAdvice。ControllerAdvice 无法捕获过滤器和拦截器的异常根据上面说的执行顺序,如果在过滤器和拦截器中抛出异常,那么 ControllerAdvice 无法捕获,因为还没执行到 ControllerAdvice 就抛出异常停止执行了。所以如果是在 Controller 层或更下面的 Service 层和 DAO 层,是可以被捕获异常的,但是在 Controller 层之前抛出了异常就无法捕获。使用 ControllerAdvice 对过滤器(Filter)中的异常捕获我们明白运行的原理以后,想要使用 ControllerAdvice 对过滤器(Filter)中的异常捕获,就需要抛出异常以后继续向后面传递执行,而不是在过滤器(Filter)中抛出异常。根据运行原理,我们这样做:
代码案例如下:在过滤器(Filter)中:
public class DemoFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try{
// 假设在这里会抛出一个 ExpiredJwtException 异常
filterChain.doFilter(servletRequest, servletResponse);
}catch (ExpiredJwtException e){
// 将异常对象设置到 Attribute 属性中
servletRequest.setAttribute("filter.error", e);
// 告诉 Dispatcher 处理的 Controller
servletRequest.getRequestDispatcher("/error/exthrow").forward(servletRequest, servletResponse);
}
}
}
新建一个接收异常的 Controller:
@Controller
public class ExceptionThrowController {
@RequestMapping("/error/exthrow")
public void returnThrow(HttpServletRequest request) throws Exception {
// 从 Attribute 属性中取出异常对象,重新在 Controller 层抛出
throw ((Exception) request.getAttribute("filter.error"));
}
}
到这里,ControllerAdvice 就可以捕获这个异常了:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = ExpiredJwtException.class)
public ApiResult<?> expiredJwtExceptionHandler(ExpiredJwtException e){
return ApiResult.builder()
.code(HttpStatus.UNAUTHORIZED)
.message("JWT expired")
.build();
}
}
明白其原理,你写代码会游刃有余。或者你有更好的解决办法吗?欢迎在评论区中分享你的方案。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。