处理rake任务失败而不中止

时间:2014-05-12 19:57:28

标签: ruby-on-rails rake

我有这个佣金任务:

desc "get product image urls from ItemMaster"
task :get_product_image_urls => :environment do
    require 'item_master'
    ItemMaster.get_image
end

它调用这个API方法,迭代数千个数据库项,如下所示:

class ItemMaster
    include HTTParty
format :xml

base_uri 'https://api.myapi.com/v2'


def self.get_image
    @items = Item.all 
    @items.each do |item|
        response = get("/item?upc=#{item.upc}&epl=100&ef=png", :headers => {"username" => "myname", "password" => "mypass"})
        image_link = response["items"]["item"]["media"]["medium"]["url"]
        item_image = ItemImage.where(:upc => item.upc).first_or_create
        item_image.update_attributes(:url => "#{image_link}")
    end
  end
end

当我调用它时,rake任务启动,直到它在约22个项目中遇到此错误:

undefined method `[]' for nil:NilClass
/Users/name/Rails/SG/lib/item_master.rb:12:in `block in get_image'
/Users/name/Rails/SG/lib/item_master.rb:10:in `each'
/Users/name/Rails/SG/lib/item_master.rb:10:in `get_image'
/Users/name/Rails/SG/lib/tasks/get_product_image_urls.rake:4:in `block in <top (required)>'
/Users/name/.rvm/gems/ruby-1.9.3-p429/bin/ruby_noexec_wrapper:14:in `eval'
/Users/name/.rvm/gems/ruby-1.9.3-p429/bin/ruby_noexec_wrapper:14:in `<main>'

第12行就是这个人:image_link = response["items"]["item"]["media"]["medium"]["url"]所以我认为api中可能缺少一个url而导致rake任务失败。有没有办法移过这样的错误并继续执行其余的rake任务?提前谢谢!

1 个答案:

答案 0 :(得分:1)

需要编辑ItemMaster.get_image方法,以便首先不创建异常条件,或者在适当的异常上进行救援并继续。有关异常处理的更多信息:http://www.tutorialspoint.com/ruby/ruby_exceptions.htm

一个例子是:

def self.get_image
    @items = Item.all 
    @items.each do |item|
        response = get("/item?upc=#{item.upc}&epl=100&ef=png", :headers => {"username" => "myname", "password" => "mypass"})
        begin
          image_link = response["items"]["item"]["media"]["medium"]["url"]
          item_image = ItemImage.where(:upc => item.upc).first_or_create
          item_image.update_attributes(:url => "#{image_link}")
        rescue NoMethodError => ex
          logger.error "Failed to locate image link ..." # Customize this to your liking
        end
    end
  end
end

为了获得额外的好处,请考虑在单独的方法中处理每个项目的代码,以便您可以在Item模型本身中隔离处理与项目相关的代码的责任!