Ruby:两次挽救相同的错误类型

Tom*_*oli 1 ruby exception-handling exception

是否可以在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
Run Code Online (Sandbox Code Playgroud)

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

dav*_*nes 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! }
Run Code Online (Sandbox Code Playgroud)