1

Is there a way to create a centralized exception handling mechanism in spring boot. I have a custom exception that I am throwing from multiple @Component classes and I would like it to be caught in one class/handler.

This is NOT a REST API or Controller triggered call. I tried @ControllerAdvice with @ExceptionHandler. but no luck. Example below to shows what I am trying to achieve. Method Handle is not triggering. I am using spring boot v2.1.1

CustomException

public class CustomException extends RuntimeException {
    public CustomException(String errorMessage, Throwable err) {
       super(errorMessage, err);
    }
}

Handler

@ControllerAdvice
public class CatchCustomException {       
   @ExceptionHandler(value = CustomException.class )
   public void handle (CustomException e)
   {
     System.out.println(e.getMessage());
   }
}

Component Class

@Component
@EnableScheduling
public class HandlingExample {

    @Scheduled(fixedRate = 3000)
    public void method1(){
        throw new CustomException("Method1++++", new Exception());
    }

    @Scheduled(fixedRate = 1000)
    public void method2(){
        throw new CustomException("Method2----", new Exception());
    }
}
J S
  • 175
  • 1
  • 4
  • 14
  • No, and it doesn't make sense; MVC controllers have a well-defined workflow and context in which they operate (i.e., "we're processing a Web request and encountered an error so return some sort of response that indicates the error"), while Spring components can do *anything*. The location of an exception is critical. You could perhaps, if you like, turn exceptions into Spring application events and publish them. – chrylis -cautiouslyoptimistic- Dec 13 '18 at 02:47
  • Have a look at https://stackoverflow.com/questions/45706159/how-to-catch-non-mvc-and-non-rest-exceptions-in-spring-boot – alediaferia Jan 09 '20 at 17:32

1 Answers1

0

spring have many error handlers in different context, for your case, you should handle the error exception with @Schedule, so you can create a TaskScheduler by your own

    @Bean
    public TaskScheduler taskScheduler() {
        ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
        ConcurrentTaskScheduler taskScheduler = new ConcurrentTaskScheduler(localExecutor);
        taskScheduler.setErrorHandler(new YourErrorHandler());
        return taskScheduler;
    }


    public class YourErrorHandler implements ErrorHandler {

        @Override
        public void handleError(Throwable t) {
            // TODO Auto-generated method stub

        }

    }
clevertension
  • 6,929
  • 3
  • 28
  • 33
  • Thanks for the suggestion. The schedule example in the code above was for demoing my question, I don't use schedule. And I take from your answer that Spring does NOT have a centralized mechanism to capture application exceptions not generated by a controller call. – J S Dec 13 '18 at 10:44