rubyfullcontact

How to run a "if" statement on returned 404s from external API call ruby


I'm testing out the Fullcontact API to retrieve information about specific people. If the person that I'm looking up with their API doesn't exist in their database it would return a 404 Not found error. I'm trying to get around that by retrieving other usernames, but it's not working. Here's the code:

  person = FullContact.person(email: 'wilson@wilsontest.com')
  if person.to_i > 400
        person = FullContact.person(email: 'wilsonp@gmail.com')
     else 
        person = FullContact.person(email: 'wilson@wilsontest.com')
     end
    p person

This still displays the 404 Not found when the email isn't found.


Solution

  • If you're using the fullcontact-api-ruby gem, the FullContact.person call should raise a FullContact::NotFound error if the person doesn't exist. You'd need to rescue that error to try something else:

    def get_person
    
      emails ||= ['wilson@wilsontest.com', 'wilsonp@gmail.com']
      person = FullContact.person(email: emails.shift)
    
    rescue FullContact::NotFound
    
      unless emails.empty?
        retry
      else
        # bottom line
      end
    
    end
    

    Note that exceptions are pretty slow in Ruby, and you're also hitting an external API, so be mindful of the response time here.