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());
}
}