1

是否可以在 ruby​​ 中多次挽救相同的错误类型?我需要像这样使用 Koala facebook API 库:

begin
  # Try with user provided app token
  fb = Koala::Facebook::API.new(user_access_token)
  fb.put_connections(user_id, {}) # TODO
rescue AuthenticationError
  # User access token has expired or is fake
  fb = Koala::Facebook::API.new(APP_FB_TOKEN)
  fb.put_connections(user_id, {}) # TODO
rescue AuthenticationError
  # User hasn't authed the app on facebook
  puts "Could not authenticate"
  next
rescue => e
  puts "Error when posting to facebook"
  puts e.message
  next
end

如果没有办法两次挽救相同的错误,是否有更好的方法来推理这个问题?

4

2 回答 2

8

您可能应该将其重构为两个单独的方法 - 一个authenticate处理异常的“安全”方法和一个authenticate!引发异常的“不安全”方法。authenticate应定义为authenticate!

这是一个如何做到这一点的示例,其中引入了重试实现。

编辑:重构以使重试独立于authenticate方法。

def authenticate!
  fb = Koala::Facebook::API.new(user_access_token)
  fb.put_connections(user_id.to_s, )
end

def authenticate
  authenticate!
rescue => e
  warn "Error when posting to facebook: #{e.message}"
end

# @param [Integer] num_retries number of times to try code
def with_retries(num_retries=2)
  yield
rescue AuthenticationError
  # User hasn't authed the app on facebook
  puts "Could not authenticate"
  # Retry up to twice
  (num_retries-=1) < 1 ? raise : retry
end

# Authenticate safely, retrying up to 2 times
with_retries(2) { authenticate }

# Authenticate unsafely, retrying up to 3 times
with_retries(2) { authenticate! }
于 2013-05-17T05:59:02.010 回答
4

我认为唯一的方法是在子句中添加一个新try-rescue子句rescue

begin
  # Try with user provided app token
  fb = Koala::Facebook::API.new(user_access_token)
  fb.put_connections(user_id, {}) # TODO
rescue AuthenticationError
  begin
    # User access token has expired or is fake
    fb = Koala::Facebook::API.new(APP_FB_TOKEN)
    fb.put_connections(user_id, {}) # TODO
  rescue AuthenticationError
    # User hasn't authed the app on facebook
    puts "Could not authenticate"
    next
  end
rescue => e
  puts "Error when posting to facebook"
  puts e.message
  next
end
于 2013-05-17T06:00:34.337 回答