【问题标题】:Can CsvHelper be configured to suppress all parsing and conversion exceptions?是否可以将 CsvHelper 配置为抑制所有解析和转换异常?
【发布时间】:2020-12-09 20:11:05
【问题描述】:

是否可以配置CsvHelper 以便它调用BadDataFoundReadingExceptionOccurred 而不是抛出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&lt;int&gt;手动阅读,那么你必须自己处理异常。

标签: .net csvhelper


【解决方案1】:

您可以检查类型是否为TypeConverterException

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

【讨论】:

  • 我认为问题在于 OP 试图手动读取“我在调用 GetField 时继续出现运行时异常”。手动读取记录时不会自动处理异常。 Configuration.ReadingExceptionOccured 永远不会被击中。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2013-11-06
  • 2021-12-12
  • 2014-03-29
  • 2015-04-11
相关资源
最近更新 更多