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

141 Views Asked by At

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: '[email protected]')
  if person.to_i > 400
        person = FullContact.person(email: '[email protected]')
     else 
        person = FullContact.person(email: '[email protected]')
     end
    p person

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

1

There are 1 best solutions below

1
Drenmi On BEST ANSWER

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 ||= ['[email protected]', '[email protected]']
  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.