@Async and errors
The starter registers Spring Boot's applicationTaskExecutor bean (alias taskExecutor), which switches @Async on for @EventListener methods: such a listener runs later instead of inside the call that published the event. Errors of scheduled runs are logged and the task keeps its schedule, unless an ErrorHandler bean takes them.
Why
Some reactions to an event should not slow the code that published it: sending a confirmation mail after an order, writing an audit entry. And a scheduled task that fails once (a server briefly down) must not stop for good, nor fail silently.
Example
@Component()
class Mailer {
// The order is confirmed without the publisher waiting for the mail.
@EventListener()
@Async() // or @Async('mailExecutor') for another TaskExecutor bean
Future<void> onPlaced(OrderPlaced order) => sendConfirmation(order);
}
// Every failed run is reported, and the task keeps running.
@Component()
class ReportErrors implements ErrorHandler {
@override
void handleError(Object error, StackTrace stackTrace) =>
crashReporter.record(error, stackTrace);
}
TaskExecutor
- The
applicationTaskExecutorbean is aSimpleAsyncTaskExecutorof the core: it runs each task in a later event-loop turn and logs its errors. - Declaring your own
TaskExecutorbean replaces it. - Having an executor switches
@Asyncon for@EventListenermethods, as Spring's@EnableAsyncdoes.@Async('name')picks anotherTaskExecutorbean. @Asyncworks on@EventListenermethods only.- There is no thread pool: everything runs on Dart's event loop.
spring.task.execution.*is not read.
See @Async for the listener side.
Errors of scheduled runs
An exception of a run, thrown or from the returned Future, is logged at error level to the spring.scheduling logger with the task's name, and the task keeps its schedule. Handle errors in the method if you need retries or alerts, or declare an ErrorHandler bean, which then receives every error instead of the log.
- The scheduler uses the only
ErrorHandlerbean, or the primary one; with several and none primary, it uses none. - A handler that throws stops the task: the error is logged and the task does not run again, as with Spring's
LOG_AND_PROPAGATE. TimerTaskScheduler(errorHandler:)sets one in code.
In Spring (Java)
@EnableAsync
@Configuration
class AsyncConfig {}
@Async
@EventListener
public void onPlaced(OrderPlaced order) { ... }
No @EnableAsync: the TaskExecutor bean switches it on. @Async on other bean methods is not supported. Spring sets an ErrorHandler on its ThreadPoolTaskScheduler; here the bean is found by type.