Spring boot Non Controller Exceptions Handling - Centralized Exception Handling

一个人想着一个人 提交于 2021-02-08 11:02:37

问题


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

回答1:


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

        }

    }


来源:https://stackoverflow.com/questions/53754296/spring-boot-non-controller-exceptions-handling-centralized-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!