Ruby - 执行已过期 [英] Ruby - Execution expired

查看:158
本文介绍了Ruby - 执行已过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的红宝石代码:

I have a ruby code like this:

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

我正在收到日志:

ERROR -- : Error: execution expired

我想要块重新执行,直到成功。

I want block re-execute until it success.

我该怎么做?

推荐答案

我会扩大一下我的评论。您可以使用 retry 返回 begin

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

这将持续尝试(并记录错误),直到它工作或手动杀死它。这可能不是你想要的,因为一个小错误会让你进入一个无限循环。一个简单的方法是让它尝试10次,然后放弃:

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

这样的东西会尝试几次然后放弃。您还可以将 sleep retry 之前调用,如果要在下次尝试之前等待一下或调查异常(可能有多个 rescue 块)选择是否立即放弃,等待和重试,或立即重试。

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.

这篇关于Ruby - 执行已过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆