Search code examples
ruby-on-railsrubyapiactiveresource

Continuing loop through ResourceNotFound?


I'm looping through a set of users and as part of that, I'm doing a call to a third-party API (via the Intercom API Ruby wrapper).

The Intercom API throws an Intercom::ResourceNotFound if it can't find a user, and that stops the entire process.

I just want it to skip the user if it can't find it.

User.each do |user|
    user = Intercom::User.find_by_email(user.email) # Intercom::ResourceNotFound thrown if not found
    user.custom_data["Example"] = true
    user.save
end

Is this an issue with the Intercom Ruby wrapper? Or is there a typical Ruby or Rails way to handle this sort of thing?


Solution

  • How about just catching the Exception?

    User.each do |user|
      begin
       user = Intercom::User.find_by_email(user.email) # Intercom::ResourceNotFound thrown if not found
       user.custom_data["Example"] = true
       user.save
      rescue Intercom::ResourceNotFound
      end
    end
    

    Since you just want to skip the user if he is not found (and an exception is thrown) there is no error-handling code after the rescue. But if you would want to put some debug message or something like that, you could just write:

      rescue Intercom::Resource
        puts %{Could not work on user...}
      end