0
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.

osflw
  • 79
  • 1
  • 8

1 Answers1

0

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.

Mahmoud Ben Hassine
  • 28,519
  • 3
  • 32
  • 50
  • I understand your point is that `afterStep` is not designed for do the thing with checked exception. Thanks. Then, how can I make all subclasses of the abstract class call the same method (verification method in the text) at the end? – osflw Sep 08 '21 at 09:39
  • You are expecting to use the exception handler in `StepExecutionListener#afterStep`, but as mentioned, this won't work. So `afterStep` is not suitable for you. You can add a protected method in your tasklet and call it inside `execute`. Subclasses can then only override that method. – Mahmoud Ben Hassine Sep 09 '21 at 06:10