如何一般地将受影响的字符串记录在FormatException中?

时间:2019-02-20 09:58:48

标签: c# .net logging exception-handling

DateTime MyDateTime;
try{
    MyDateTime = DateTime.Parse(datestring, MyCultureInfo).Date;
    //many other lines
}catch(Exception e){
    Log(e);
}

我有一个解析函数,其中,string被转换为DateTime对象。在大多数情况下,这是可行的,但有时输入字符串可以使用不同的DateFormat或包含其他字符串,然后转换将失败。
要处理这些情况,我需要知道哪些字符串引起了问题。异常消息不会告诉我:

  

System.FormatException:该字符串未被识别为有效的DateTime。从索引0开始有一个未知单词。

即使转换为FormatException,异常对象也不提供有问题的输入字符串:

try{
    MyDateTime = DateTime.Parse(datestring, MyCultureInfo).Date;
    //many other lines
}catch(FormatException e){
    Log(e);
}

我需要怎么做才能得到这样的日志?

  

System.FormatException:该字符串未被识别为有效的DateTime。从索引0开始有一个未知词。
  输入:'2019.02.20'

当然我可以用一个try-catch-block包含代码中的每一行

DateTime MyDateTime;
try{
    MyDateTime = DateTime.Parse(datestring, MyCultureInfo).Date;
}catch(Exception e){
    Log(e);
    Log($"Input: '{datestring}'");
}
try{
  //many other lines
}catch(Exception e){
    Log(e);
}

但这很糟糕。

2 个答案:

答案 0 :(得分:1)

  

但这很糟糕。

是的。当您开始正确处理和记录错误时,代码大小会增加。

大多数日志记录框架都有一个Log方法,该方法带有异常和附加消息。在这种情况下,您可能可以编写如下内容:

Log(e, $"Unable to parse DateTime {datestring}");

您当然可以在DateTime.Parse周围创建一个包装器方法,这将引发其自身的异常。像这样:

private static DateTime ParseDate(string input)
{
    try
    {
        return DateTime.Parse(input, MyCultureInfo).Date;
    }
    catch (FormatException e)
    {
        throw new FormatException($"Unable to parse DateTime '{input}': {e.Message}", e);
    }
}

答案 1 :(得分:0)

是的,您将不得不针对无法使您包含字符串的所有地方提供服务。尽管我会避免通过异常进行编码,并假定会失败。例如

    var dateTimeString = "2015494";
    if(!DateTime.TryParse(dateTimeString, out DateTime result))
    {
        Log();
    }