Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the exceptions thrown from item reader?

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?

like image 942
Gopi Avatar asked Mar 13 '23 19:03

Gopi


1 Answers

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! :)

like image 87
kk_coder Avatar answered May 08 '23 01:05

kk_coder