title: How to handle Exceptions for a Custom Filter FORM_LOGIN_FILTER
body: <p>I have a custom Filter that validates a Token, tokenLoginFilter</p>
  
  <p><strong>my Spring Security xml</strong></p>
  
  <pre><code>&lt;http pattern="/api/**" use-expressions="true" create-session="stateless" entry-point-ref="restAuthenticationEntryPoint" authentication-manager-ref="authenticationManager"&gt;
      &lt;custom-filter ref="tokenLoginFilter" position="FORM_LOGIN_FILTER" /&gt;
      &lt;!--&lt;form-login authentication-success-handler-ref="mySuccessHandler" authentication-failure-handler-ref="myFailureHandler" /&gt;
      &lt;logout /&gt;--&gt;
      &lt;intercept-url pattern="/api/**" access="isAuthenticated()" /&gt;
      &lt;intercept-url pattern="/api/login/**" access="permitAll"/&gt;
  &lt;/http&gt;
  </code></pre>
  
  <p><strong>TokenLoginFilter</strong></p>
  
  <pre><code>@Component
  public class TokenLoginFilter extends GenericFilterBean {
      public static final String DEFAULT_TOKEN_AUTHENTICATION_PARAMETER_NAME = "token";
  
      @Autowired
      protected AuthenticationManager authenticationManager;
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse response,
                           FilterChain chain) throws IOException, ServletException {
          String[] parameters = request.getParameterValues(DEFAULT_TOKEN_AUTHENTICATION_PARAMETER_NAME);
  
          if (parameters != null &amp;&amp; parameters.length &gt; 0) {
              String token = parameters[0];
  
              if (token != null &amp;&amp; !token.isEmpty()) {
                  TemporaryAuthenticationToken temporaryAuthenticationToken = new TemporaryAuthenticationToken(token);
                  temporaryAuthenticationToken.setDetails(
                          new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
  
                  SecurityContextHolder.getContext().setAuthentication(
                          authenticationManager.authenticate(temporaryAuthenticationToken));
              }
          }
  
          chain.doFilter(request, response);
      }
  }
  </code></pre>
  
  <p>In the authenticationManager.authenticate call, I throw a <strong>BadCredentialsException</strong> from my <strong>TokenAuthenticationProvider</strong></p>
  
  <p><strong>TokenAuthenticationProvider</strong></p>
  
  <pre><code>@Component
  public class TokenAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
      public static final TimeZone DEFAULT_TIME_ZONE = getTimeZone("UTC");
  
      @Autowired
      protected TemporaryAuthenticationTicketService temporaryAuthenticationTicketService;
  
      @Autowired
      protected UsersService usersService;
  
      @Override
      public Authentication authenticate(Authentication authentication) throws AuthenticationException {
          if (authentication instanceof TemporaryAuthenticationToken) {
              TemporaryAuthenticationTicket temporaryAuthenticationTicket = null;
              try {
                  temporaryAuthenticationTicket = temporaryAuthenticationTicketService.find(
                          ((TemporaryAuthenticationToken) authentication).getCredentials());
              } catch (EmptyResultDataAccessException ignored) {
              }
  
              if (temporaryAuthenticationTicket != null) {
                  Calendar expirationDate = Calendar.getInstance(DEFAULT_TIME_ZONE);
                  expirationDate.setTime(temporaryAuthenticationTicket.getExpirationDate());
  
                  if (Calendar.getInstance(DEFAULT_TIME_ZONE).before(expirationDate)) {
                      Users users = usersService.findUsersUnsecure(temporaryAuthenticationTicket.getUserId());
  
                      if (users != null) {
                          UserDetails userDetails = new User(users);
  
                          return createSuccessAuthentication(userDetails, authentication, userDetails);
                      }
                  }
              } else {
                  throw new BadCredentialsException(messages.getMessage(
                          "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
              }
          }
  
          return null;
      }
  
      @Override
      public boolean supports(Class&lt;?&gt; authentication) {
          return TemporaryAuthenticationToken.class.isAssignableFrom(authentication);
      }
  
      @Override
      protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                    UsernamePasswordAuthenticationToken authentication)
              throws AuthenticationException {
      }
  
      @Override
      protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
              throws AuthenticationException {
          return null;
      }
  }
  </code></pre>
  
  <p>This <strong>BadCredentialsException</strong> is being interpreted as a error code 500 by Tomcat.</p>
  
  <pre><code>HTTP/1.1 500 Internal Server Error
  Connection: close
  Content-Language: en
  Content-Length: 3152
  Content-Type: text/html;charset=utf-8
  Date: Tue, 08 Jul 2014 17:37:55 GMT
  Server: Apache-Coyote/1.1
  
  &lt;html&gt;&lt;head&gt;&lt;title&gt;Apache Tomcat/7.0.50 - Error report&lt;/title&gt;&lt;style&gt;&lt;!--H1 {fon
  t-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:
  22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525
  D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;backgro
  und-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;col
  or:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:w
  hite;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;backgroun
  d:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR
  {color : #525D76;}--&gt;&lt;/style&gt; &lt;/head&gt;&lt;body&gt;&lt;h1&gt;HTTP Status 500 - Bad credentials
  &lt;/h1&gt;&lt;HR size="1" noshade="noshade"&gt;&lt;p&gt;&lt;b&gt;type&lt;/b&gt; Exception report&lt;/p&gt;&lt;p&gt;&lt;b&gt;mes
  sage&lt;/b&gt; &lt;u&gt;Bad credentials&lt;/u&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;description&lt;/b&gt; &lt;u&gt;The server encounter
  ed an internal error that prevented it from fulfilling this request.&lt;/u&gt;&lt;/p&gt;&lt;p&gt;&lt;
  b&gt;exception&lt;/b&gt; &lt;pre&gt;org.springframework.security.authentication.BadCredentialsE
  xception: Bad credentials
          com.neptune.unsub.security.TokenAuthenticationProvider.authenticate(Toke
  nAuthenticationProvider.java:56)
          org.springframework.security.authentication.ProviderManager.authenticate
  (ProviderManager.java:156)
          com.neptune.unsub.security.TokenLoginFilter.doFilter(TokenLoginFilter.ja
  va:38)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doF
  ilter(FilterChainProxy.java:342)
          org.springframework.security.web.context.request.async.WebAsyncManagerIn
  tegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
          org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequ
  estFilter.java:106)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doF
  ilter(FilterChainProxy.java:342)
          org.springframework.security.web.context.SecurityContextPersistenceFilte
  r.doFilter(SecurityContextPersistenceFilter.java:87)
          org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doF
  ilter(FilterChainProxy.java:342)
          org.springframework.security.web.FilterChainProxy.doFilterInternal(Filte
  rChainProxy.java:192)
          org.springframework.security.web.FilterChainProxy.doFilter(FilterChainPr
  oxy.java:160)
          org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(Dele
  gatingFilterProxy.java:343)
          org.springframework.web.filter.DelegatingFilterProxy.doFilter(Delegating
  FilterProxy.java:260)
          org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(H
  iddenHttpMethodFilter.java:77)
          org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequ
  estFilter.java:106)
          org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(
  CharacterEncodingFilter.java:88)
          org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequ
  estFilter.java:106)
          com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:169)
          com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:232)
  &lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;note&lt;/b&gt; &lt;u&gt;The full stack trace of the root cause is available
  in the Apache Tomcat/7.0.50 logs.&lt;/u&gt;&lt;/p&gt;&lt;HR size="1" noshade="noshade"&gt;&lt;h3&gt;Apac
  he Tomcat/7.0.50&lt;/h3&gt;&lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>I have tried using the Spring MVC way of handling exceptions</p>
  
  <pre><code>@ControllerAdvice
  public class GlobalExceptionHandlers extends ResponseEntityExceptionHandler {
  
      @ExceptionHandler(BadCredentialsException.class)
      public ResponseEntity&lt;String&gt; badCredentialsException(BadCredentialsException e) {
          return new ResponseEntity&lt;&gt;(e.getMessage(), UNAUTHORIZED);
      }
  
  
  }
  </code></pre>
  
  <p>But the exception is not being handled by this ExceptionHandler. How can I get Spring to intercept this Exception before Tomcat handles it?</p>