首页 > 解决方案 > httparty NoMethodError: nil:NilClass 的未定义方法“[]”

问题描述

我使用 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']

标签: ruby-on-railshttparty

解决方案


这是关于Rollbar 所说的最常见的错误之一

问题必须比json_stats['Facebook']is nil,因此访问 to['share_count']会产生错误。我建议您使用dig来防止这种不希望出现的错误,并决定什么时候json_stats['Facebook']nil.

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

推荐阅读