java - 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 不是来自“请求”而是来自“前”?
解决方案
推荐阅读
- python - 如何在一个请求中放置或删除多个对象?Django 休息
- php - ASP.NET Web API 与 PHP 的区别
- sql - 如何为postgresql中的每个用户返回具有最大值的类别?
- python - M1 Mac 的 OpenCV 问题:分配前引用了局部变量“x”
- c# - Interlocked 类是否与 FieldOffset 一起使用?
- javascript - 选择文字时自动弹出菜单
- java - 如果在同步方法中调用等待方法,我的 java 单元测试失败
- python - Python re.findall 不匹配 HTML 中的 JS 变量
- python - Flask/Jinja 错误:jinja2.exceptions.TemplateSyntaxError:预期令牌“名称”,得到“字符串”
- react-native - react-native FlatList undefined 不是对象(评估'props.getItem')