isxaker
isxaker

Reputation: 9446

How to filter out catch blocks

I need to return false prevent logging if SP.ServerException has been thrown. But in all other cases i need to do logging and return false too.

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;
}

I know the solution could be

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;
}

Upvotes: 2

Views: 77

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

In c# 6, you can filter exceptions :

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

Upvotes: 2

Waldemar
Waldemar

Reputation: 5513

Try the when keyword:

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;
}

Upvotes: 6

Related Questions