Search code examples
javascriptgoogle-apps-scriptgoogle-workspace

Check if user exists with AdminDirectory


I have a Sheet with a list of emails, and I want to create an account for emails that do not have one. So I check with

function getUserFromEmail(email) {
    return user = AdminDirectory.Users.get(email)
}

but I get this error if user does not exists, and the script then stops :

GoogleJsonResponseException: API call to directory.users.get failed with error: Resource Not Found: userKey

Do you have an idea on how I can make the error not blocking ?


Solution

  • Posting this for documentation purposes.

    As suggested by TheAddonDepot, use try...catch in order to handle situations in which the user is not found:

    function getUserFromEmail(email) {
      try {
        return user = AdminDirectory.Users.get(email);
      } catch(e) {
        console.log(e);
      }  
    }