Reputation: 7889
I'm reading a csv file with FlatFileItemReader
and using a FieldSetMapper
to map it to a domain object.
In case the mapping fails, I would like to have the original line read by the FlatFileItemReader
at my disposal so I could write it to another csv file.
My original idea was to use some listener to push the read string to StepContext
and then a SkipListener
to fetch the string to write it to another file. But I can't find a way to catch the original line read by the FlatFileItemReader
.
Suggestions?
Upvotes: 4
Views: 6560
Reputation: 5619
Implementing the onReadError(Exception) method of the ItemReadListener interface does exactly what you need.
public void onReadError(Exception e) {
if(e instanceof FlatFileParseException) {
FlatFileParseException ffpe = (FlatFileParseException) e;
ffpe.getLineNumber(); //The line number error occured
ffpe.getInput();//Text value of the unparsed line
}
}
Upvotes: 3
Reputation: 6630
if your configuration is similar to the Spring Batch Documentation for FlatFileItemReader, you could use a custom LineMapper instead of the usual DefaultLineMapper which throws an enriched exception
here is some simple example code
public class DefaultLineMapper<T> implements LineMapper<T>, InitializingBean {
(...)
public T mapLine(String line, int lineNumber) throws Exception {
try {
return fieldSetMapper.mapFieldSet(tokenizer.tokenize(line));
}
catch (...) {
throw new CustomException(line, lineNumber);
}
}
}
Upvotes: 2