【发布时间】:2021-07-12 18:59:53
【问题描述】:
在考虑使用 CsvHelper 导入 csv 数据时的“数据”验证时,我希望使用 .Validate 方法将所有“数据”验证代码放入 ClassMap。
我一直在寻找如何使用 .Validate 方法来确保数据符合我的业务规则并在违反验证规则时向用户发送好的错误消息的好例子强>。
一个非常基本的示例位于 CsvHelper 网站的“示例”部分的“配置/类映射/验证代码”中:https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation/
我能够预测并捕获我使用 .Validate 方法设置的错误。但是,我还没有确定一种方法来向我的用户提供足够的信息以在遇到问题时解决问题。在我看来,FieldValidationException 没有包含足够有用的信息。我看到其他人问这个问题,但我看到的其他帖子对这个问题没有足够的答案。请在下面查看我的代码和 cmets。
class Program
{
static void Main(string[] args)
{
try
{
// load comma separated data into string for processing
var s = new StringBuilder();
s.AppendLine("Id,Name");
s.AppendLine("1,one-e");
// Begin processing
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<FooMap>();
var contents = csv.GetRecords<Foo>().ToList();
Console.WriteLine($"Read file: length is : {contents.First().Id},{contents.First().Name},{contents.First().Date}");
}
}
catch (FieldValidationException fieldExc)
{
// this exception object does not appear to hold any information about the column that is in error. It does not seem to specify what the error entails.
// It appears to contain the value that created the exception? In a 'string' field called: "Field".
// I would really like further information about what is specifically is wrong with which column and possibly which row.
Console.WriteLine($"Error Message is : {fieldExc.Message}");
}
catch(TypeConverterException converterExc)
{
// If I happen to have a conversion exception, then the resulting TypeConversionException has good information to advise
// a user to correct an error.
var message = FriendlyErrorText(converterExc);
Console.WriteLine(message);
}
catch (Exception exc)
{
Console.WriteLine($"Error Message is : {exc.Message}");
}
finally
{
Console.WriteLine("test executed");
Console.ReadKey();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset? Date { get; set; }
}
public class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Name).Validate(field => !field.Field.Contains("-"));
}
}
public static string FriendlyErrorText(TypeConverterException exception)
{
var column = exception?.MemberMapData?.Member?.Name ?? "Unknown";
string typeConversion;
switch (exception?.TypeConverter?.ToString())
{
case "Int32Converter":
typeConversion = "integer";
break;
default:
typeConversion = exception?.TypeConverter?.GetType()?.Name ?? "Unknown";
break;
}
var message = $"There was an error importing the text data '{exception?.Text ?? "Unknown"}' into the column {column}. The target column is of type {typeConversion}";
return message;
}
}
【问题讨论】: