Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 916
Sayuj Avatar asked Jun 14 '11 06:06

Sayuj


People also ask

What is expired execution?

This means that your destination server is taking too long or is breaking the connection. We suggest that you wait for some time and try again, since your server might be overloaded. If this happens often however, you'll have to contact your host.

What is Net :: OpenTimeout?

Net::OpenTimeout is raised when a connection cannot be created within a specified amount of time. Getting this error a few times isn't always out of the ordinary, but you may want to add some error handling.


1 Answers

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.

like image 86
mu is too short Avatar answered Sep 18 '22 23:09

mu is too short