Ruby rescue and retry specific code block

谁都会走 提交于 2019-12-10 13:11:36

问题


I have the following code in my script...

  begin
    #Loop to create 1000 emails...
    #Loop to send 1000 emails...

  rescue Timeout::Error => e
    retry_attempts += 1
    if retry_attempts < 10
      retry
    else
      puts "Timeout error, deleting emails...".red
      logs.puts("Rescued a timeout error...#{e}")
      email_ids_all.each do |email_delete|
        #delete all email...
      end

My question is what retry is actually going to "retry". If the script has already generated 1000 emails in one loop and sent 999 of them in another loop, and then it times out on sending the 1000th email- Will it retry the specific line of code it encountered the error on, will it start the loop over with the 1000th email, will it start the entire loop over, or will it start at the beginning of the script running through both loops?

I am using ruby 1.9.3.


回答1:


retry will execute the entire begin block, so in your case all the email loops will run again.

Here's a quick example, which will print integers 1 through 7 continuously (terminate with CTRL-C, as it will infinite loop):

begin
  (1..10).each do |x|
    puts x
    if x > 6
      STDIN.gets # press enter to do another iteration
      raise ArgumentException
    end
  end
rescue
  retry # loop will restart from 1
end


来源:https://stackoverflow.com/questions/18518863/ruby-rescue-and-retry-specific-code-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!