Search code examples
ruby-on-railsrubyactiverecordrescue

Rails 4 – How to rescue from NoMethodError and continue trying method?


In my Contacts class, after a contact is created with their email address, I try to pull as much contact data from FullContact's API as possible.

I'm having this issue where if one column of data doesn't exist for a "person" in FullContact, it throws a NoMethodError and I don't get to save the rest of the data that potentially does exist to the contact, because my method stops at the error.

How can I rescue from a NoMethodError and get my method to continue running the rest of it? Like for it to just skip over the error and try the rest of the code. I've tried next and continue in my rescue code but that doesn't work.

Thanks for any help.

class Contact < ActiveRecord::Base  
  belongs_to :user

  after_create do |contact|
    contact.delay.update_fullcontact_data
  end

  def update_fullcontact_data

    person = FullContact.person(self.email) 

    if person.contact_info.given_name.present? 
      self.name = person.contact_info.given_name 
    end

    if person.contact_info.family_name.present? 
      self.last_name = person.contact_info.family_name
    end

    if person.demographics.location_general.present?
      self.city = person.demographics.location_general
    end

    save!

  rescue NoMethodError => exception
   puts "Hit a NoMethodError"
   save!
  end
end

Solution

  • in general what may be a solution for your problem is try method (http://apidock.com/rails/Object/try). To make the story short - it returns nil instead of raising exception if method does not exist on specific object