我看到一个 pull request 应该解决澄清错误消息的问题,但它仍然不能提供足够的灵活性。
目前我必须写这样的东西,以便为用户提供更好的错误细节:
``` c#
var e = 新列表
csvReader.Configuration.ReadingExceptionCallback = (ex, row) =>
{
foreach(ex.Data.Values 中的 var 错误)
{
var info = error.ToString().Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var value = info[4].Split(':')[1].Trim();
var field = info[3].Split(':')[1].Trim();
e.Add(string.Format("无法读取行 {1} 中的值 {0},字段 {2}。",
值,行。行,字段));
}
};
// 返回 e 到网页(例如作为 JSON)
This is relatively ok. It gives information where exactly parsing error has occured. However, as you can see, digging this information is ugly since I have to parse string to get the value and the field name. It would be nice if this information could be exposed via properties so that I could write something like this:
``` c#
csvReader.Configuration.ReadingExceptionCallback = (ex, row) =>
{
foreach (var error in row.Errors)
{
e.Add(string.Format("Could not read value {0} in row {1}, field {2}.",
error.Value, error.Row, error.FieldName));
}
};
但上面没问题......它有效。 更重要的是下面的请求。
能够提供解析失败的原因也很好。
假设一个字段只接受值“红色”或“蓝色”,但用户输入“黄色”。 我们可以通过以下方式解决:
c#
// in the MyClassMap : CsvClassMap<MyClass> class
Map(x => x.Color).ErrorMessage("Accepted values are 'Red' and 'Blue'");
...
// in the ReadingExceptionCallback
e.Add(string.Format("Could not read value {0} in row {1}, field {2}. {3}",
error.Value, error.Row, error.FieldName, error.Message));
这种语法将为开发人员提供很大的灵活性,并向用户提供清晰的反馈。
让我知道你的想法。
这是一个有趣的想法。 我现在将其标记为一个功能,稍后再深入研究。
只想支持此功能请求。
既然我在这里,我只想简单地说声谢谢。 CsvHelper 在很多层面上都很棒。
在 3.0 中,基础CsvHelperException
对象现在具有所有值的属性。 回调将返回CsvHelperException
而不是Exception
。 3.0 测试版在 NuGet 上。
最有用的评论
这是一个有趣的想法。 我现在将其标记为一个功能,稍后再深入研究。