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

问题描述 投票:0回答:2
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);
}

但那很糟糕。

c# .net logging exception-handling
2个回答
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);
    }
}

0
投票

是的,您将不得不满足每个无法使您包含字符串的地方。虽然我会避免通过异常编码和代码来假设它会失败。例如。

    var dateTimeString = "2015494";
    if(!DateTime.TryParse(dateTimeString, out DateTime result))
    {
        Log();
    }
© www.soinside.com 2019 - 2024. All rights reserved.