如何在"ReaderListener/WriterListener"中使用"onReadError/onWriteError"来处理异常

How to use "onReadError/onWriteError" in "ReaderListener/WriterListener" to handle exceptions

只是抛出异常,不会运行"onReadError"

PS:mst_employees1是一个不存在的数据table模拟异常

    @Bean
    private Step step1(MyBatisCursorItemReader<MstEmployeesEntity> myBatisReader,FlatFileItemWriter<MstEmployeesEntity> CSVWriter){
        return stepBuilderFactory
                .get("step1")
                .listener(stepListener)
                .<MstEmployeesEntity,MstEmployeesEntity>chunk(1)
                .reader(myBatisReader)
                .listener(readerListener)
                .processor(myPorcessor)
                .writer(CSVWriter)
                .build();
    }
    @Bean
    @StepScope
    public MyBatisCursorItemReader<MstEmployeesEntity> myBatisReader(@Value("#{jobParameters['para1']}") Integer pk) {
        Map<String, Object> map = new HashMap<>();
        map.put("employeePk",pk);
        return new MyBatisCursorItemReaderBuilder<MstEmployeesEntity>()
                .sqlSessionFactory(sqlSessionFactory)
                .queryId("jp.armg.toughness.datasource.mapper.BatchMstEmployeesEntityMapper.exmapleSelect")
                .parameterValues(map)
                .build();
    }

工作Class

public class ReaderListener implements ItemReadListener<MstEmployeesEntity> {

    @Override
    public void onReadError(Exception ex) {
        // TODO Auto-generated method stub
        System.out.println("++++++++++++++++++++++++++++++++++++++");
        System.out.println("on read error: " + ex.getMessage());
        System.out.println("======================================");
    }
}

读取监听器

<mapper namespace="jp.armg.toughness.datasource.mapper.BatchMstEmployeesEntityMapper">
    <select id="exmapleSelect" resultType="jp.armg.toughness.datasource.entity.MstEmployeesEntity">
        select * from mst_employees1 where employee_pk &lt; #{employeePk};
    </select>
</mapper>

映射器

org.springframework.batch.item.ItemStreamException: Failed to initialize the reader
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:152) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader$$FastClassBySpringCGLIB$$ebb633d0.invoke(<generated>) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]

控制台

只是抛出异常,不会运行"onReadError"

PS:mst_employees1是一个不存在的数据table模拟异常

mst_employees1 is a data table that does not exist to simulate anomalies

这种异常应该在初始化 reader 时(作为当前行为)而不是在读取项目时以快速失败的方式进行检查。 ItemReadListener 是为项目读取期间可能发生的错误而设计的,而不是在 reader.

的初始化期间发生的错误

因此,如果您真的想为这种情况编写单元测试,您的测试应该尝试使用不存在的 table 初始化 reader 并期望 ItemStreamException