简体   繁体   中英

Spring boot Non Controller Exceptions Handling - Centralized Exception Handling

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

spring have many error handlers in different context, for your case, you should handle the error exception with , so you can create a 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

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM