我尝试用AuthenticationException
来捕捉@ExceptionHandler
。我可以通过两种方式捕获AuthenticationException
:
第一种方法是使用我的unsuccessfulAuthentication
类中的JwtAuthenticationFilter
方法,该方法扩展了UsernamePasswordAuthenticationFilter
。
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
resolver.resolveException(request, response, null, exception);
}
第二种方法是使用AuthenticationEntryPoint:
@Component()
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
resolver.resolveException(request, response, null, exception);
}
}
但是在两种情况下,resolver
为空,而我的@ExceptionHandler
没有被调用。
我缺少什么?
我试图创建另一个bean HandlerExceptionResolver并将其直接传递给构造函数。在这种情况下,resolver
不为null,但不会再次调用@ExceptionHandler
。
这是堆栈跟踪:
2019-06-19 16:12:47.093错误14754 --- [nio-8090-exec-2] o.a.c.c.C。[。[。[/]。[dispatcherServlet]:的Servlet.service() servlet [dispatcherServlet]抛出异常
java.lang.NullPointerException:空
在com.jv.scred.security.RestAuthenticationEntryPoint.commence(RestAuthenticationEntryPoint.java:27) 〜[classes /:na]
在org.springframework.security.web.access.ExceptionTranslationFilter.sendStartAuthentication(ExceptionTranslationFilter.java:213) 〜[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
在org.springframework.security.web.access.ExceptionTranslationFilter.handleSpringSecurityException(ExceptionTranslationFilter.java:185) 〜[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
在org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:141) 〜[spring-security-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]