Ruby - Execution expired
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?
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.
精彩评论