gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:36 25 4
gpt4 key购买 nike

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

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

最佳答案

您应该将其重构为两个单独的方法 - 一个处理异常的“安全”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! }

关于Ruby:两次拯救相同的错误类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16602288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com