httparty NoMethodError:nil:NilClass的未定义方法`[]'

时间:2018-05-07 15:57:21

标签: ruby-on-rails httparty

我使用Ruby 2.5.0,httparty gem 我的模特

class FeedEntry
  include Mongoid::Document
  include Mongoid::Timestamps

  field :guid, type: String
  field :url, type: String
  field :share_count, type: Integer, default: 2

  before_update :share_info

  def share_info
    checked_url = self.url
    json_stats = HTTParty.get("http://api.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.credentials.socialshared_api_key}", timeout: 180, open_timeout: 1200)
    self.share_count = json_stats['Facebook']['share_count']
  end
end

当我尝试解析时,我有这个错误

NoMethodError: undefined method `[]' for nil:NilClass

/Users/ipatov/rails_projects/apps/tm/app/models/feed_entry.rb:71:in `share_info'

71行 self.share_count = json_stats ['Facebook'] ['share_count']

1 个答案:

答案 0 :(得分:3)

这是关于Rollbar says

的最常见错误之一

问题必须超过json_stats['Facebook'] nil,因此访问['share_count']会产生错误。我建议您使用dig来防止此意外错误,并在json_stats['Facebook']nil时决定该怎么做。

    self.share_count = json_stats.dig('Facebook', 'share_count')