Spring Batch: Listener event when Tasklet throws an exception

风流意气都作罢 提交于 2019-12-01 11:39:48

You can

  1. manage exception into tasklet
  2. store error into execution-context/external bean
  3. manage error from stepExecutionListener

or in StepExecutionListener.afterStep(StepExecution stepExecution) lookup into stepExecution.getFailureExceptions()

I guess its too late now. But I recently came across this problem. It is easier to handle exception with ChunkListener, however exception handling can be done in Tasklet's RepeatStatus execute(StepContribution s, ChunkContext chunkContext) method (well, it is the only method that Tasklet interface has ^^). What you need is a try/catch block to catch the exceptions. However you will need to throw the caught exception again in order to roll back the transaction. Here is a code-snippet. In my case, I had to stop the job if some data could not be read due to Database server shutdown.

@Override
public RepeatStatus execute(StepContribution s, ChunkContext chunkContext){
    try{
        getAllUsersFromDb(); // some operation that could throw an exception
        // doesn't hurt to put all suspicious codes in this block tbh
    }catch(Exception e){
        if(e instanceof NonSkippableReadException){
            chunkContext.getStepContext().getStepExecution().getJobExecution().stop();
        }
        throw e;
    }
    return RepeatStatus.FINISHED;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!