title: How to catch AccessDeniedException in Spring Boot REST API
body: <p>I have a simple Spring Boot REST API with 2 endpoints, one is protected one is not. For the one is protected, I want to catch the <code>AccessDeniedException</code> and send a 401 rather than the default 500 error. Here is my security configuration:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter{
  
  @Override
  public void configure(WebSecurity webSecurity) {
      webSecurity.ignoring().antMatchers("/");
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http
              .exceptionHandling()
              .accessDeniedHandler(new AccessDeniedHandler() {
                  @Override
                  public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access.AccessDeniedException accessDeniedException) throws IOException, ServletException {
                      System.out.println("I am here now!!!");
                  }
              });
  
      http
              .addFilterAfter(getSecurityFilter(), FilterSecurityInterceptor.class);
      http
              .sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
      http
              .csrf()
              .disable();
      http
              .authorizeRequests()
              .antMatchers("/protected").anonymous();
  }
  
  public Filter getSecurityFilter() {
      return new Filter() {
          @Override
          public void init(FilterConfig filterConfig) throws ServletException {
              //do nothing here
          }
  
          @Override
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              String appKeyHeaderValue = ((HttpServletRequest)request).getHeader("X-AppKey");
              if(appKeyHeaderValue!=null &amp;&amp; appKeyHeaderValue.equals("MY_KEY")) {
                  chain.doFilter(request,response);
              } else {
                  throw new AccessDeniedException("Access denied man");
              }
          }
  
          @Override
          public void destroy() {
  
          }
      };
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I never see my <code>I am here now!!!</code> print statement, what I instead see is the default page
  <code>
  Whitelabel Error Page
  This application has no explicit mapping for /error, so you are seeing this as a fallback.
  Tue Jul 25 23:21:15 CDT 2017
  There was an unexpected error (type=Internal Server Error, status=500).
  Access denied man
  </code>
  Notice how my <code>Access denied man</code> does get printed from when the exception is being thrown.</p>
  
  <p>When I run the project, I also see the following in the console:
  <code>
  2017-07-25 23:21:14.818  INFO 3872 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity&lt;java.util.Map&lt;java.lang.String, java.lang.Object&gt;&gt; org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
  2017-07-25 23:21:14.818  INFO 3872 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
  </code></p>
  
  <p>Here is how my project structure looks like:</p>
  
  <p><a href="https://i.stack.imgur.com/TKqCO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TKqCO.png" alt="enter image description here"></a></p>