处理Spring中过滤引发的exception

我正在尝试实现一个Custom ExceptionTranslationFilter,以便处理我的所有关于身份validation的exception(在我的自定义filter类中,身份validation期间使用的toke的有效性)。 根据在互联网上搜索,没有适当的java配置的可用来源。 请参阅我当前的配置。

protected void configure(HttpSecurity http) throws Exception { http.anonymous().and() .servletApi().and() .headers().and() .authorizeRequests() .antMatchers("/api/login").permitAll() .anyRequest().authenticated().and() .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class) .addFilterAfter(new ExceptionTranslationFilter(new AuthenticationExceptionHandler()),ExceptionTranslationFilter.class); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } 

自定义validation入口点类:

 public class AuthenticationExceptionHandler implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"UNAUTHORIZED"); } } 

validationfilter类:

 public class StatelessAuthenticationFilter extends GenericFilterBean { public StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, AuthenticationException { //I forced my filter to throw this Exception just to test if my ExceptionTranslationFilter in the configuration works. throw new MyAuthenticationException("This is a test for filters"); } } 

这里当前的问题是我期待与未授权的Http状态相关的错误响应,即401,但我得到错误500,而是返回exception消息和堆栈跟踪。