0

I am use the FileHelper to parse CSV files. Error messages encountered when parsing the file are displayed to the end user. The end user may not be able to make sense of the technical error message. Not too many clerks know what an Int32 is or Class: UploadFooDto.

I would like to customize the error messages so they are more user friendly. Something like:

  • Line 1. Column 2. A string (a) was entered instead of a number
  • Line 2. Column 3. '13-14-15' is not a valid date

I cannot find anything in the API that would allow me to customize the error messages. The most I have so far are some extension methods to clean up the errors:

public static class FileHelperExceptionExtensions
{
    public static string BuildMessage(this ErrorInfo error)
    {
        if (error.ExceptionInfo is ConvertException)
        {
            return ((ConvertException)error.ExceptionInfo).BuildMessage();
        }

        if (error.ExceptionInfo is BadUsageException)
        {
            var message = error.ExceptionInfo.Message;
            var readTo = message.IndexOf("Class:");
            return message.Substring(0, readTo);
        }

        return string.Format("Line: {0}. An unspecific error occured.", error.LineNumber);
    }

    public static string BuildMessage(this ConvertException exception)
    {
        return string.Format("Line: {0}. Column: {1}. Field: {2}. Cannot convert '{3}' to type: '{4}'", exception.LineNumber, exception.ColumnNumber, exception.FieldName, exception.FieldStringValue, exception.FieldType.Name);
    }
}

but these extensions still leave a lot to be desired. Is it possible to customize the error messages?

4

1 に答える 1

0

価値以上に手間をかけずに拡張メソッドを改善することは困難です。

デフォルトのコンバーターをサブクラス化することはできません (たとえば、およびでFileHelpers.ConvertHelpers.Int32Converterあるため)。タイプごとに独自のカスタム コンバーターを作成できます(そして、FileHelpers の対応するソース コードに基づいて作成します)。次に、メッセージを別の方法でフォーマットする代替を発生させることができます(サブクラス化することもできません)。internalsealedInt32ConverterConvertExceptionsealed

于 2012-11-08T13:52:29.967 に答える