【发布时间】:2020-12-09 20:11:05
【问题描述】:
是否可以配置CsvHelper 以便它调用BadDataFound 或ReadingExceptionOccurred 而不是抛出TypeConverterExceptions?我有处理程序连接这些,但我继续在调用 GetField<int> 时遇到运行时异常。
明确地说,我知道数据有什么问题。关键是我希望能够向用户报告这些问题,以便他们修复数据。虽然我可以打电话给TryGetField,但这太冗长了,因为我想在每个领域都这样做。
这就是我的代码的样子。请注意,我将错误累积为异常列表。
using var cr = new CsvReader(reader, CultureInfo.InvariantCulture);
cr.Configuration.HasHeaderRecord = false;
var errors = new List<Exception>();
cr.Configuration.ReadingExceptionOccurred = exception =>
{
errors.Add(exception);
return true;
};
cr.Configuration.BadDataFound = context =>
errors.Add(new Exception("Bad data found at line " + context.RawRow + " position " + context.CurrentIndex));
cr.Configuration.MissingFieldFound = (headerNames, index, context) =>
errors.Add(new Exception("Missing fields " + headerNames.JoinToString() +" at line " + context.RawRow + " position " + context.CurrentIndex));
【问题讨论】:
-
如果您调用了
GetRecords(),您将在ReadingExceptionOccurred中捕获TypeConverterException。这是GetRecords()内部构建的框架的一部分。如果你使用GetField<int>手动阅读,那么你必须自己处理异常。