2016-03-29 70 views
1

我正在使用rake任務從一個csv獲取數據,使用該數據調用shopify api,並將響應保存到另一個CSV。問題是我沒有錯誤處理程序,因此如果shopify api無法找到我提供的資源,則整個任務會中止。處理錯誤的最佳方法是什麼,以便如果在Shopify中找不到資源,只需跳過它並進入下一行?Rake任務句柄404

行調用shopify API在下面的代碼是:
variant = ShopifyAPI::Variant.find(vid)

namespace :replace do 
    desc "replace variant id with variant sku" 

    task :sku => :environment do 
     file="db/master-list-3-28.csv" 
     newFile = Rails.root.join('lib/assets', 'newFile.csv') 
     CSV.open(newFile, "a+") do |csv| 
      CSV.foreach(file) do |row| 

       msku, namespace, key, valueType, value = row 
       valueArray = value.split('|') 
       newValueString = "" 

       valueArray.each_with_index do |v, index| 

        recArray = v.split('*') 
        handle = recArray[0] 
        vid = recArray[1] 
        newValueString << handle 
        newValueString << "*" 
        # use api call to retrieve variant sku using handle and vid 
        #replace vid with sku and save to csv 

        variant = ShopifyAPI::Variant.find(vid) 
        sleep 1 
        # puts variant.sku 
        newValueString << variant.sku 
        if index < 2 
         newValueString << "|" 
        end 
       end 

       #end of value save the newvaluestring to new csv 
       csv << [newValueString] 

      end 
     end 
    end 
end 

回答

1

這裏有一個簡單的方法來完成它:

begin 
    variant = ShopifyAPI::Variant.find(vid) 
rescue 
    next 
end 

如果將引發異常的東西救援發生。