'GraphClientService throws exception when calling 'Any'

Given a GUID, I need to know if a user exists in azure active directory.

If I pass the Id of an exisitng user everything is Ok.
If I pass the id for which no user account exists, I get the following exeption:

ServiceException: Code: Request_ResourceNotFound Message: Resource '02803255-b96e-438a-9123-123' does not exist or one of its queried reference-property objects are not present.

I know this record doen not exist, as this is what I'm testing, I want false to be returned somehow. Surely I do not have to catch the exception?

//Simple code:
    public bool CheckUserExists(string userId) {
        bool exists = false;
        //purposefully set this to a string that does not match any user.
        userId = "02803255-b96e-438a-9123-123";
        var user = _graphServiceClient
            .Users
            .Request()
            .Filter("Id eq '" + userId + "'")
            .GetAsync();
        //exception thrown on next line.
        if (user.Result.Count == 1) {
            exists = true;
        }


Solution 1:[1]

Please try checking if user count is less than or equals 0 condition , instead if count equals 1.

    var users = await graphClient.Users.Request().GetAsync();
         var exists=true;
       try {
                var user = _graphServiceClient
                  .Users
                  .Request()
                  .Filter("Id eq '" + userId + "'")
                  .GetAsync(); 


             if (user.Count <= 0) {
                   exists = false;
                      break;
                         }
            } 
      catch (ServiceException ex) {
           exists = false;
                        }

return exists;

or try with

 if (user.Count !=null && user.Count>=0)

Reference:

  1. verify if user account exists in azure active directory -SO reference
  2. Microsoft.Azure.ActiveDirectory.GraphClient/User

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kavyasaraboju-MT