【问题标题】:Rails 4 – How to rescue from NoMethodError and continue trying method?Rails 4 – 如何从 NoMethodError 中解救并继续尝试方法?
【发布时间】:2015-06-01 17:53:07
【问题描述】:

在我的联系人类中,使用他们的电子邮件地址创建联系人后,我会尝试从 FullContact 的 API 中提取尽可能多的联系人数据。

我遇到了这个问题,如果 FullContact 中的“人”不存在一列数据,它会引发 NoMethodError,并且我无法将可能确实存在的其余数据保存到联系,因为我的方法在错误处停止。

如何从 NoMethodError 中解救并让我的方法继续运行其余部分?就像它跳过错误并尝试其余代码一样。我在我的救援代码中尝试了nextcontinue,但这不起作用。

感谢您的帮助。

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

【问题讨论】:

  • 我不认为像这样拯救 NoMethodError 是一个好主意......你最终可能会遇到意外行为的麻烦,比如你打错字,但它仍然会拯救它并保存,你不知道它来自哪里
  • 好点。但是,我目前仍在从 NoMethodError 中解救,因为我认为最好保存从 FullContact 提取的任何数据,考虑到我们为每次成功的 api 调用付费。对替代品持开放态度。
  • 你也可以使用.respond_to?检查一个方法是否存在,而不是尝试点击它并从异常中拯救(对于非 Rails 应用程序)

标签: ruby-on-rails ruby activerecord rescue


【解决方案1】:

一般来说,解决您的问题的方法是try 方法(http://apidock.com/rails/Object/try)。简而言之 - 如果特定对象上不存在方法,它返回 nil 而不是引发异常

【讨论】:

  • 嗯 @djaszczurowski 你将如何使用我提供的代码来做到这一点?
  • if person.try(:contact_info).try(:family_name).present? self.last_name = person.contact_info.family_name end 如果contact_info 方法得到保证,那么我会打电话给if person.contact_info.try(:family_name).present?
【解决方案2】:

如果您只是想确保保存,可以使用ensure 执行以下操作:

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!

  ensure
   save!
  end
end

更多信息: http://blog.rubybestpractices.com/posts/rklemme/003-The_Universe_between_begin_and_end.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2017-03-07
    相关资源
    最近更新 更多