.net - 是否可以将 CsvHelper 配置为抑制所有解析和转换异常?
问题描述
是否可以进行配置CsvHelper
,而不是抛出TypeConverterException
s,而是调用BadDataFound
或ReadingExceptionOccurred
代替?我有处理程序连接这些,但我继续在调用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));
解决方案
您可以检查类型是否为TypeConverterException
.
cr.Configuration.ReadingExceptionOccurred = exception =>
{
if (exception is TypeConverterException)
{
errors.Add(exception);
return false;
}
return true;
};
推荐阅读
- erlang - 无法在 ejabberd-18.01 中编译 mod_mam_sql
- python - 在 Python 中使用 matplotlib 在 4x4 多图上的 X 和 Y 刻度
- java - 带有图像的网格视图上的 android 搜索视图没有给出正确的搜索结果。
- apache-flink - Apache Bean 2.4.0 与 Apache Flink 1.5
- spring - 使用 Amazon MQ 作为 Spring Websockets + STOMP 的代理中继
- css - CSS对齐文本,使其成直线
- python - 如果 type 为 None 或 NoneType,则返回其他内容
- c# - 从输入中删除多余空格并显示正确间隔的输出的程序
- django - 特定于主机的请求会中断不相关的测试用例
- java - 没有注释的 Guice 构造函数注入?