如何处理异常并跳过错误的 csv 行?
How to handle exception and skip the wrong csv line as well?
我正在使用 Spring batch
读取 csv
文件。我正在阅读 csv
的内容,并根据 entity
class.
之一将此内容写入数据库
现在 csv 中可能有某些行是错误的并且与 POJO 属性不匹配。为了处理这个问题,我配置了我的 Step
如下:
Step step = stepBuilderFactory.get("CSV-Step")
.<Book, Book>chunk(100)
.faultTolerant()
.skip(FlatFileParseException.class)
.skipLimit(1)
.reader(itemReader)
.writer(itemWriter)
.build();
它基本上跳过导致 FlatFileParseException
的行并继续后续行。现在我还想记录无法完成解析的行。为此,在我用 @ControllerAdvice
注释的 GlobalExceptionHandler
中,我做了以下方法:
@OnReadError
public void handleCsvParseException(FlatFileParseException ex, Throwable throwable) {
logger.error("! FlatFileParseException, line is: " + ex.getLineNumber());
logger.error("! FlatFileParseException, input is: " + ex.getInput());
logger.error("! Message: " + throwable.getMessage());
logger.error("! Cause: " + throwable.getCause());
}
问题是这个方法没有被调用,因为我的 Step
中有 skip
配置。我如何忽略不需要的行,即跳过不需要的行,但同时记录有关它们的信息。如果能提供任何帮助,我将不胜感激。
SkipListener 正是您所需要的。只要在读取、处理或写入项目期间发生配置的可跳过异常,就会调用此侦听器。
对于您的情况,您可以在 SkipListener#onSkipInRead(Throwable t);
方法中实现日志记录逻辑。 FlatFileParseException
将作为参数传递,并为您提供必要的上下文(行号和原始输入)。
希望对您有所帮助。
我正在使用 Spring batch
读取 csv
文件。我正在阅读 csv
的内容,并根据 entity
class.
现在 csv 中可能有某些行是错误的并且与 POJO 属性不匹配。为了处理这个问题,我配置了我的 Step
如下:
Step step = stepBuilderFactory.get("CSV-Step")
.<Book, Book>chunk(100)
.faultTolerant()
.skip(FlatFileParseException.class)
.skipLimit(1)
.reader(itemReader)
.writer(itemWriter)
.build();
它基本上跳过导致 FlatFileParseException
的行并继续后续行。现在我还想记录无法完成解析的行。为此,在我用 @ControllerAdvice
注释的 GlobalExceptionHandler
中,我做了以下方法:
@OnReadError
public void handleCsvParseException(FlatFileParseException ex, Throwable throwable) {
logger.error("! FlatFileParseException, line is: " + ex.getLineNumber());
logger.error("! FlatFileParseException, input is: " + ex.getInput());
logger.error("! Message: " + throwable.getMessage());
logger.error("! Cause: " + throwable.getCause());
}
问题是这个方法没有被调用,因为我的 Step
中有 skip
配置。我如何忽略不需要的行,即跳过不需要的行,但同时记录有关它们的信息。如果能提供任何帮助,我将不胜感激。
SkipListener 正是您所需要的。只要在读取、处理或写入项目期间发生配置的可跳过异常,就会调用此侦听器。
对于您的情况,您可以在 SkipListener#onSkipInRead(Throwable t);
方法中实现日志记录逻辑。 FlatFileParseException
将作为参数传递,并为您提供必要的上下文(行号和原始输入)。
希望对您有所帮助。