我有一个rake任务,它循环遍历CSV文件中的行,并且在该循环内,有一个begin / rescue块来捕获任何可能的引发异常。但是当我运行它时,它总是说“耙子中止了!”而且它没有进入救援区
CSV.foreach(path, :headers => true) do |row|
id = row.to_hash['id'].to_i
if id.present?
begin
# call to mymethod
rescue => ex
puts "#{ex} error executing task"
end
end
end
...
def mymethod(...)
...
begin
response = RestClient.post(...)
rescue => ex
raise Exception.new('...')
end
end
预期:它应该完成循环CSV的所有行
实际结果:它在达到“ raise”异常后停止,并说:
耙子中止了!
异常:错误消息在这里
...
原因:
RestClient :: InternalServerError:500内部服务器错误
答案 0 :(得分:1)
您可以使用next
跳过错误的循环步骤:
CSV.foreach(path, :headers => true) do |row|
id = row.to_hash['id'].to_i
if id.present?
begin
method_which_doing_the_staff
rescue SomethingException
next
end
end
end
并在方法内部引发异常:
def method_which_doing_the_staff
stuff
...
raise SomethingException.new('hasd')
end
答案 1 :(得分:0)
我通过注释掉引发异常的行来解决了这个问题,因为这似乎是目前最快的解决方案。
# raise Exception.new('...')
如果有更好的方法,我仍然愿意接受其他建议。