title: What is the difference between response.sendError() and throwing an exception using the throw keyword?
body: <p>What is the difference between the two approaches below?</p>
  
  <p><strong><em>Case 1:</em></strong></p>
  
  <pre><code>    public void onFail(HttpServletResponse response, org.springframework.security.authentication.BadCredentialsException exception)
           response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage());
      }
  </code></pre>
  
  <p>In this case I get this output and I <em>can</em> control the HTTP status code:</p>
  
  <pre><code>    {
        "timestamp": 1458974564628,
        "status": 401,
        "error": "Unauthorized",
        "message": "Authentication Failed: null",
        "path": "/api/myservice1"
      }
  </code></pre>
  
  <p><strong><em>Case 2:</em></strong></p>
  
  <pre><code>    public void onFail(){
                  throw new BadCredentialsException("Invalid token");
      }
  </code></pre>
  
  <p>In this case I get this output and I <em>can't</em> control the HTTP status code,</p>
  
  <pre><code>    {
        "timestamp": 1458974259995,
        "status": 403,
        "error": "Forbidden",
        "exception": "org.springframework.security.authentication.BadCredentialsException",
        "message": "Access Denied",
        "path": "/api/myservice1"
      }
  </code></pre>
  
  <p>In case 2, where and how is the 403 status mapped to a <code>BadCredentialsException</code>? How can I override it and send a 401 response instead of a 403 response?</p>
  
  <p>I am using Spring Boot with Spring Security.</p>