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

时间:2013-05-17 05:51:42

标签: ruby exception exception-handling

是否可以在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

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

2 个答案:

答案 0 :(得分: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! }

答案 1 :(得分: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