我正在使用rake任务从一个csv获取数据,使用该数据调用shopify api,并将响应保存到另一个CSV。问题是我没有错误处理程序,所以如果shopify api找不到我提供的资源,整个任务就会中止。处理错误的最佳方法是什么,以便在Shopify中找不到资源时,只需跳过它并继续下一行?
以下代码中调用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
答案 0 :(得分:1)
这是完成任务的简单方法:
begin
variant = ShopifyAPI::Variant.find(vid)
rescue
next
end
如果出现异常,则会发生救援事件。