title: How to handle UsernameNotFoundException spring security
body: <p>How to handle <code>UsernameNotFoundException</code> ?</p>
  
  <p>In spring security when username not found the <code>UserDetailsService</code> implementation throws a <code>UsernameNotFoundException</code>. For example like this: </p>
  
  <pre><code>   @Override
     @Transactional
     public UserDetails loadUserByUsername(java.lang.String username) throws UsernameNotFoundException {
         logger.info("Load user by username: {}", username);
         User user = userRepository.findUserByUsername(username).orElseThrow(
                     () -&gt; new UsernameNotFoundException("User Not Found with -&gt; username or email: " + username));
  
         return UserPrinciple.build(user);
     }
  </code></pre>
  
  <p>I would like to build a custom "User not found REST response".
  How should I catch/handle this exception? I have implemented a handler method in the  WebSecurityConfigurerAdapter implementation the handler:</p>
  
  <pre><code>  private static void handleException(HttpServletRequest req, HttpServletResponse rsp, AuthenticationException e)
             throws IOException {
         PrintWriter writer = rsp.getWriter();
         writer.println(new ObjectMapper().writeValueAsString(new AuthResponse("", null, null, null, null,
                 "Authentication failed.", false)));
         rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
     }
  </code></pre>
  
  <p>But this method should wait for an  <code>AuthenticationException</code> exception which, and during runtime the type of the exception is <code>java.lang.NullPointerException</code> so I'm not able to cast or retrieve the the initial <code>UsernameNotFoundException</code>.</p>
  
  <p>Any advice would be appreciated. 
  Many many regards :).</p>