gpt4 book ai didi

ruby-on-rails - 如何在 rake 任务中捕获引发的异常

转载 作者:行者123 更新时间:2023-12-04 17:41:29 24 4
gpt4 key购买 nike

我有一个循环遍历 CSV 文件中的行的 rake 任务,在该循环中,有一个开始/救援 block 来捕获任何可能引发的异常。但是当我运行它时,它一直在说“rake aborted!”而且它没有进入救援区

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 的所有行

实际结果:它在到达“引发”异常后停止说:

rake aborted!

Exception: error message here

...

Caused by:

RestClient::InternalServerError: 500 Internal Server Error

最佳答案

你可以使用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

关于ruby-on-rails - 如何在 rake 任务中捕获引发的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com