title: Handling Filter Thrown Exceptions in Spring
body: <p>I am trying to implement an Custom ExceptionTranslationFilter in order to handle all of my exception in regards of the authentication ( in which the validity of the toke to be used during authentication happens on my custom filter class). As per searching on the internet there are no available sources for the proper java configuration. Please see my current configuration.</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>Custom Authentication Entry Point Class:</p>
  
  <pre><code>public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
      httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"UNAUTHORIZED");
    }
  }
  </code></pre>
  
  <p>Authentication Filter Class:</p>
  
  <pre><code>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");
    }
  }
  </code></pre>
  
  <p>The current problem here is that I am expecting an Error response related to the Unauthorized Http status which is 401 but I am getting the error 500 instead and the exception message and the stack trace is being returned instead.</p>