【问题标题】:How to filter out catch blocks如何过滤掉捕获块
【发布时间】:2016-11-06 08:40:32
【问题描述】:

如果SP.ServerException 被抛出,我需要return false 阻止记录。 但在所有其他情况下,我也需要进行日志记录和return false

try
{
    folder = GetFolderByRelativeUrl(folderRelativePath);
}
catch (SP.ServerException serverEx)
{
    //if file is not found the logging is not need
    if (serverEx?.Message == "File not found")
    {
        return false;
    }
    //how i can go from here
}
catch (Exception ex)
{
    //to there
    Log(ex.Message);
    return false;
}

我知道解决办法是

try
{
    folder = GetFolderByRelativeUrl(folderRelativePath);
}
catch (Exception ex)
{
    //if file is not found the logging is not need
    if (!(ex is SP.ServerException && ex?.Message == "File not found"))
    {
        Log(ex.Message);
    }

    return false;
}

【问题讨论】:

  • 你的代码有什么问题?这似乎是合理的。我更喜欢针对特殊异常情况的显式单独的 catch 块,而不是类型检查 if 语句。
  • 我想我的代码一切正常 =)

标签: c# .net exception try-catch


【解决方案1】:

试试when 关键字:

try
{
    folder = GetFolderByRelativeUrl(folderRelativePath);
}
catch (SP.ServerException serverEx) when (serverEx.Message == "File not found")
{
   return false;
}
catch (Exception ex)
{
    //to there
    Log(ex.Message);
    return false;
}

【讨论】:

  • 这正是我想要的
  • 在 +1 之前从未听说过when
  • 这是 C# 6 的一个特性
【解决方案2】:

在 c# 6 中,您可以过滤异常:

catch (SP.ServerException ex ) when (ex.Message == "File not found")

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2020-11-18
    • 2022-01-23
    • 1970-01-01
    • 2011-03-06
    相关资源
    最近更新 更多