【问题标题】:CsvHelper: Data Validation exceptions do not provide adequate information about exception to be helpfulCsvHelper:数据验证异常未提供有关异常的足够信息以提供帮助
【发布时间】: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;
        }
    }


【问题讨论】:

    标签: c# csv csvhelper


    【解决方案1】:

    FieldValidationException 包括 CsvContext,它包含您需要的大部分内容。

    catch (FieldValidationException fieldExc)
    {
        var message = string.Empty;
        var headerIndex = fieldExc.Context.Reader.CurrentIndex;
        if(fieldExc.Context.Reader.HeaderRecord[headerIndex].ToLower() == "name")
        {
            message = "Name cannot contain a dash.";
        }
        
        Console.WriteLine($"Error Message is : Field Validation Exception on Row: {fieldExc.Context.Parser.Row}, Message: {message} Original Text: \"{fieldExc.Field}\"");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      相关资源
      最近更新 更多