0

我似乎在重用相同rescue的 s. 有没有可能有rescue块?所以而不是:

while count != 0 do 
<<code>>
rescue error1
<<code>>
retry
rescue error2
<<code>>
break
end

我可以有:

def rescue_block
rescue error 1
<<code>>
retry
rescue error 2
<<code>>
break
end

while count !=0
<<code>>
rescue_block
end

注意breakretryrescue_block动作需要应用于循环,而不是自身。

编辑:

使用 Twitter gem,Twitter 的大部分错误都可以以相同的方式处理(即,如果您达到 API 限制,请稍候。)。完整代码:

while cursor != 0 do
  begin
    grabFollowers ? f = Twitter.follower_ids(username,{:cursor=>cursor}) : f = Twitter.friend_ids(username,{:cursor=>cursor})
    outfile.puts(f.ids) if writeHumanReadable
    arrayOfIds << f.ids
    cursor = f.next_cursor
  rescue Twitter::Error::Unauthorized
    break
  rescue Twitter::Error::BadRequest
    #ran out of OAUTH calls, waits until OAUTH reset + 10 seconds.
    outErrorFile = File.new("#{username.to_s}-ERROR.txt",'w')
    resetTime = Twitter.rate_limit_status.reset_time_in_seconds
    current = Time.now.to_i
    pauseDuration = resetTime-current+10
    outErrorFile.puts(Time.now)
    outErrorFile.puts(pauseDuration/60)
    outErrorFile.close
    sleep(pauseDuration)
    retry
  rescue Twitter::Error::NotFound
    break
  rescue Twitter::Error::ServiceUnavailable
    sleep(60*5)
    retry
  end
  sleep(2)
end
4

1 回答 1

3

您的示例使它看起来像您想要 Ruby 没有的宏。

我们可以通过块非常接近您的示例,但是在不了解您的用例的情况下很难回答这个问题。(我想你没有使用异常来进行流量控制,这通常是不受欢迎的,因为流量控制不是例外情况)。

根据您要执行的操作, throw 和 catch 可能比异常更适合您的需求。

class Example
  RetryException = Class.new StandardError
  BreakException = Class.new StandardError

  attr_accessor :count

  def initialize
    self.count = 10
  end

  def rescue_block
    yield
  rescue RetryException
    self.count -= 1
    retry
  rescue BreakException
    self.count -= 2
    return
  end

  def count_down
    rescue_block { yield count while 0 < count }
  end
end

Example.new.count_down do |count|
  count # => 10, 9, 8, 7, 6, 5
  raise Example::BreakException if count == 5
  raise Example::RetryException
end

Example.new.count_down do |count|
  count # => 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
  raise Example::RetryException
end
于 2012-02-04T19:25:19.077 回答