title: Handle 401 Error (Spring Security)
body: <p>I can handle 404 error.</p>
  
  <pre><code>@ResponseStatus(value = HttpStatus.NOT_FOUND)
      @ExceptionHandler(NoHandlerFoundException.class)
      @ResponseBody
      public void noHandlerFoundException (HttpServletResponse response) throws IOException{
         //some code
      }
  </code></pre>
  
  <p>But how to handle 401 error?</p>
  
  <p><strong>Edit</strong> I am using Java and not web.xml</p>
  
  <p><strong>Edit</strong> What should I put in NoHandlerFoundException to handle the HttpStatus.UNAUTHORIZED</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I have method unsuccessfulAuthentication, when authentication failed:</p>
  
  <pre><code>public class StatelessLoginFilter extends AbstractAuthenticationProcessingFilter { 
  
      protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                        AuthenticationException failed) throws IOException, ServletException {
                  SecurityContextHolder.clearContext();
  
                  if (logger.isDebugEnabled()) {
                      logger.debug("Authentication request failed: " + failed.toString());
                      logger.debug("Updated SecurityContextHolder to contain null Authentication");
                      logger.debug("Delegating to authentication failure handler " + failureHandler);
                  }
  
          //        response.setCharacterEncoding("UTF-8");
          //        response.getWriter().write(jsonService.toString(jsonService.getResponse(false, "Не удалось авторизоваться", "401")));
  
                  rememberMeServices.loginFail(request, response);
                  failureHandler.onAuthenticationFailure(request, response, failed);
  
              }
          }
  </code></pre>
  
  <p>This code sent 401 error html. I need to send json, you can see it in comments.</p>