spring security 中捕获过滤器异常
当使用 spring security 的 onceperrequestfilter 时,捕获过滤器中抛出的异常可能存在问题。本文探讨了如何捕获此类异常。
@component
public class jwtauthenticationtokenfilter extends onceperrequestfilter {
@override
protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception {
// 尝试解析 jwt,如果失败则抛出 customexception
try {
// 解析 jwt
...
} catch (exception e) {
throw new customexception(customexceptiontype.need_login, "登录信息过期,请重新登录");
}
// 继续处理请求
filterchain.dofilter(request, response);
}
}通常,使用 @exceptionhandler 注解无法捕获过滤器中的异常,因为这些异常会在过滤器层面本身被处理。spring security 具有一个专门用于处理安全异常的过滤器,该过滤器优先于其他全局异常处理机制。
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.filter.OncePerRequestFilter;
@RestController
public class FilterErrorController extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 抛出自定义异常
throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "需要登录");
}
}添加此过滤器后,spring security 会将此过滤器放在异常处理链的最前面。它会捕获所有过滤器中的异常并将其转换成 http 响应,而不会让它们进入servlet容器的异常处理机制。因此,@exceptionhandler 注解无法拦截这些异常。
以上就是Spring Security中OncePerRequestFilter异常如何有效捕获?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号