Ruby - Execution expired

£可爱£侵袭症+ 提交于 2019-12-22 04:59:35

问题


I have a ruby code like this:

begin
  doc = Nokogiri::HTML(open(url).read.strip)
rescue Exception => ex
  log.error "Error: #{ex}"
end

And I am getting log as:

ERROR -- : Error: execution expired

I want block re-execute until it success.

How can I do it?


回答1:


I'll expand on my comment a little bit. You can use retry to go back to the begin:

begin
  doc = Nokogiri::HTML(open(url).read.strip)
rescue Exception => ex
  log.error "Error: #{ex}"
  retry
end

That will keep trying (and logging errors) until it works or you manually kill it. That's probably not what you want though as one little mistake will send you into an infinite loop. An easy way around that is to let it try for, say, 10 times and then give up:

MAX_ATTEMPTS = 10

doc = nil
begin
  doc = Nokogiri::HTML(open(url).read.strip)
rescue Exception => ex
  log.error "Error: #{ex}"
  attempts = attempts + 1
  retry if(attempts < MAX_ATTEMPTS)
end

if(doc.nil?)
  # Do something about the persistent error
  # so that you don't try to access a nil
  # doc later on.
end

Something like this will try a few times and then give up. You could also put a sleep call before the retry if you want to wait a bit before the next attempt or investigate the exception (possibly with multiple rescue blocks) to choose if you should give up immediately, wait and retry, or retry immediately.



来源:https://stackoverflow.com/questions/6340051/ruby-execution-expired

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