Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Universal exception handler for @Scheduled tasks in Spring (Boot) with Java configuration

I have lots of scheduled tasks in my Spring Boot (ver 1.4.2) application and would like to catch all exceptions from them using one handler like is possible for normal controllers with @ExceptionHandler annotation. This approach does not work for tasks that are defined with @Scheduled annotation because of threading:

@Component
public class UpdateJob {
    @Transactional
    @Scheduled(cron = "0 1 0 * * *")
    public void runUpdateUsers() {
        userService.updateUsers();
    }

    @ExceptionHandler
    public void handle(Exception e) {
       // some more logic here
       logger.error(e.getMessage());
    }

 }

@ExceptionHandler does not work for @Scheduled method (and it turns out it is not meant to). Instead, Spring Boot uses it's own LoggingErrorHandler:

2016-12-08 15:49:20.016 ERROR 23119 --- [pool-7-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

Can I somehow replace or supply default exception handler for scheduled tasks? Or would it make sense (and is it possible) to switch to PropagatingErrorHandler which as I understand propagates the error further? Is there any other way to achieve the goal using only Java configuration (no XML)?

This is not a duplicate of this question as it explicitly asks for a solution based on Java configuration, not XML (so it is decent to incorporate into Spring Boot project without any XML configuration).

There are also some answers that demonstrate how to configure TaskScheduler from the scratch. Eg this answer requires that you also define pool size, max pool size, queue capacity. Here is a solution which also need very extensive configuration. Documentation shows how to configure other aspects, but not how to specify error handling. But what is the minimal required effort with Java config so that I can maximally keep Spring Boot default values (thread pools, executor configurations etc).

like image 627
MF.OX Avatar asked Dec 08 '16 14:12

MF.OX


1 Answers

Here is an example of setting custom error handler (Spring 2.0.2):

@Bean
public TaskScheduler taskScheduler() {
    ConcurrentTaskScheduler scheduler = new ConcurrentTaskScheduler();
    scheduler.setErrorHandler(throwable -> { /* custom handler */ });
    return scheduler;
}
like image 181
yurez Avatar answered Sep 21 '22 19:09

yurez