首页 > 解决方案 > Spring为什么要改变异常的类型

问题描述

我有一个 JWT 过滤器,它可以抛出 JWTDecodeException

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    final JwtService jwtService;

    public JwtAuthenticationTokenFilter(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = jwtService.extractToken(request);
        if (StringUtils.hasLength(token)) {
            DecodedJWT decodedJWT = jwtService.validateToken(token);
            JwtAuthenticationToken authentication = new JwtAuthenticationToken(decodedJWT);
            authentication.setAuthenticated(true);
            SecurityContextUtils.setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}

我也有一个处理所有异常的错误处理程序

@RequestMapping("/error")
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> test(Exception ex, WebRequest request) {
    if (ex instanceof AccessDeniedException || ex instanceof JWTDecodeException) {
        System.out.println(123);
    }
    return handleExceptionInternal(ex, "test", new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}

但我无法捕获 JWTDecodeException,因为出于某种原因,'ex' 参数存储了简单的异常。我用调试跟踪它并看到我的 JWTDecodeException 何时变为异常,但我不明白如何避免它。此外,我可以JWTDecodeExceptiont = (JWTDecodeException)request.getAttribute("javax.servlet.error.exception",0);在处理程序中使用它,它将返回 JWTDecodeException。

有没有办法让 JWTDecodeException 不是来自“请求”而是来自“前”?

标签: javaspringspring-bootexception

解决方案


推荐阅读