我使用FileHelper解析CSV文件。分析文件时遇到的错误消息显示给最终用户。最终用户可能无法理解技术错误信息。没有太多的职员知道什么是Int32
或Class: UploadFooDto
。FileHelper库 - 自定义错误消息
我想定制错误消息,以便它们更加用户友好。喜欢的东西:
- 行1列2的字符串(一)中输入的不是数字
- 行2列3 '13 -14-15' 不是一个有效的日期
我在API中找不到任何可以定制错误消息的东西。到目前为止,我得到的最多的是一些扩展方法来清除错误:
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);
}
}
但是这些扩展仍然有很多不足之处。是否可以自定义错误消息?
我唯一的变化是将ConvertException转换为一个局部变量,使用“var convertInfo = error.ExceptionInfo as ConvertException;”然后检查null,这样你就不会做两次类型检查。 – netniV