title: Request scoped bean exceptions and @ControllerAdvice
body: <p>I have a custom Spring Boot <code>AutoConfiguration</code> class in which I’m creating a <code>@RequestScop</code>ed bean of a custom class - <code>Foo</code>. In the same <code>AutoConfiguration</code> class, I’m creating a bean of my global exception handler which is a <code>@ControllerAdvice</code>. All these classes are a packaged as a jar and used as a dependency in my other Spring Boot web application. Whenever there’s an exception in a controller method, the appropriate exception handler is invoked in my global exception handler, except whenever there is an exception in <code>Foo</code>, a <code>BeanCreationException</code> is thrown and none of the global exception handlers get invoked. I tried adding <code>@Order(Ordered.HIGHEST_PRECEDENCE)</code> as suggested in some SO answers, but none of them worked. Is it possible to handle such request scoped bean exceptions in the global exception handler - a <code>@ControllerAdvice</code>? Much appreciated.</p>
  
  <p><strong>EDIT</strong>
  This is my <code>AutoConfiguration</code> class. (This is in a different jar)</p>
  
  <pre><code>@Configuration
  @ConditionalOnClass({FooContext.class, MyGlobalExceptionHandler.class})
  public class AutoConfiguration {
  
      // This bean is used in a Controller
      @Order
      @RequestScope
      @Bean
      @ConditionalOnMissingBean(FooContext.class)
      public FooContext fooContext() throws IOException {
          // generateFooContext() throws the exception and Spring wraps it with BeanCreationException.
          return FooContextFactory.generateFooContext(); 
      }
  
      @Bean
      @ConditionalOnMissingBean
      public MyGlobalExceptionHandler globalExceptionHandler(MyErrorHelper errorHelper) {
          return new MyGlobalExceptionHandler (errorHelper);
      }
  }
  </code></pre>
  
  <p>This is <code>MyGlobalExceptionHandler</code>(This is in a different jar)</p>
  
  <pre><code>@ControllerAdvice
  @RefreshScope
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public class MyGlobalExceptionHandler {
  
      // Never invoked 
      @ExceptionHandler(Exception.class)
      public ResponseEntity&lt;ErrorResponse&gt; render(Exception ex) {
          log.error("Exception occurred: ", ex);
          return errorHelper.throwErrorException(DEFAULT_ERROR_CODE, HttpStatus.INTERNAL_SERVER_ERROR);
      }
  
      /// ... 
  }
  </code></pre>