How to handle the exceptions thrown from item reader?

拥有回忆 提交于 2019-12-07 08:32:46

问题


I want to catch the exceptions thrown from item reader (e.g. reader not open , incorrect token exceptions etc) and handle it. Currently spring batch is throwing them as fatal exceptons and come out of the step.

Please let me know if there is any way to do it?


回答1:


I faced the same issue whereby I wanted to catch the org.springframework.batch.item.file.FlatFileParseException thrown by the FlatFileItemReader and perform some custom handling & logging. Did some research and almost reached the conclusion that I might have to write a custom reader instead of the default reader I was currently using, until I stumbled upon a gem of a section in the Spring Batch documentation: http://docs.spring.io/spring-batch/reference/html/configureStep.html#interceptingStepExecution

You can write a custom implementation of the ItemReadListener<T> interface and over-ride the onReadError(Exception ex) method and then register this listener class in the corresponding step. As such, this method will then be called when the reader encounters an exception while reading from the file. The exception reference will be passed to the method as well using which you can do as you please like logging etc. Similarly, writing a @OnReadError annotated method is also an alternative if you don't want to implement the ItemReadListener interface separately.

On a different note, if your whole purpose is to skip such exceptions that might occur while reading, you can try adding following to the chunk configuration in the XML:

<skippable-exception-classes>
     <include class="org.springframework.batch.item.file.FlatFileParseException"/>
</skippable-exception-classes>

Ref: http://docs.spring.io/spring-batch/reference/html/configureStep.html#configuringSkip

Problem solved! :)



来源:https://stackoverflow.com/questions/34435817/how-to-handle-the-exceptions-thrown-from-item-reader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!