public class TaskletConfiguration { ... @Bean public Step step() { return steps.get("step") .tasklet(tasklet) .exceptionHandler(logExceptionHandler()) // Handler for logging exception to specific channel .build(); } @Bean public Job job() { return jobs.get("job") .start(step()) .build(); } } public class ExampleTasklet implements Tasklet, StepExecutionListener { ... @Override public RepeatStatus execute(...) throws Exception { // Do my tasklet // Throw if it fails, and be handled by logExceptionHandler() } @Override public ExitStatus afterStep(StepExecution stepExecution) { // Want to throw so that logExceptionHandler() can handle it as throwing in execute(). throwable_function(); } }
This is my example code using tasklet in spring boot.
My problem is: I want to throw exception from afterstep()
, but the interface does not allow it.
Despite this limitation, why I obsessed with afterstep()
is that I want to make abstract class to make Tasklet template which can verify each execution in afterstep()
. I want verification to run after all execute()
is done, which will be overridden by subclass. So I have no choices but using afterstep()
.
Any idea to run verification method after each execute()
with throwable or afterstep()
can pass Exception to logExceptionHandler()
? I hope to define logExceptionHandler()
in TaskletConfiguration
class. It will be obese if it is defined in Tasklet class, as I will make abstract class, which will be inherited by many subclasses.
Advertisement
Answer
The StepExecutionListener#afterStep
is not designed to throw checked exceptions. Here is an excerpt from its Javadoc:
Called after execution of step's processing logic (both successful or failed). Throwing exception in this method has no effect, it will only be logged.
Moreover, even if you throw a (runtime) exception in afterStep
, the exception won’t be passed to the exception handler, it will only be logged as mentioned in the Javadoc.
I think it is too late to throw exceptions in StepExecutionListener#afterStep
, this method can be used to check the status of the step execution and modify the ExitStatus if needed to drive the rest of the job execution flow.