首页 > 解决方案 > 是否可以将 CsvHelper 配置为抑制所有解析和转换异常?

问题描述

是否可以进行配置CsvHelper,而不是抛出TypeConverterExceptions,而是调用BadDataFoundReadingExceptionOccurred代替?我有处理程序连接这些,但我继续在调用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));

标签: .netcsvhelper

解决方案


您可以检查类型是否为TypeConverterException.

cr.Configuration.ReadingExceptionOccurred = exception =>
{           
    if (exception is TypeConverterException)
    {
        errors.Add(exception);
        return false;
    }
    
    return true;
};

推荐阅读