如何过滤掉catch块

时间:2016-07-04 15:03:25

标签: c# .net exception try-catch

如果return false被抛出,我需要SP.ServerException阻止日志记录。 但在所有其他情况下,我需要进行日志记录和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;
}

2 个答案:

答案 0 :(得分:6)

尝试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 :(得分:2)

在c#6中,您可以过滤例外:

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