我正在使用OAuth2以以下格式发出请求:
@access_token = get_access_token
begin
@access_token.get(...).body
rescue OAuth::Error => e
# handle errors
end
这有效,但它可以挽救所有 OAuth2 错误,我只想挽救特定错误。
例如,如果我只想拯救未经授权的错误。是否有类似OAuth::Error::Unauthorized
的东西,或者只是使用响应代码OAuth::Error::401
.
有没有办法限制我从哪些OAuth
错误中拯救
我不知道OAuth::Error是否有子类。
但这里有一种普遍适用的方法来挽救特定错误。
begin
# raise error here
rescue OAuth::Error => e
puts e.class # => OAuth::Error or some subclass
if e.class == OAuth::Error::SomeSubclass
# continue with rescue
else
raise e # the equivalent of "super" from a rescue block
# i.e. act like the rescue didn't happen
end
end
除了在e.class
上使用if
之外,您还可以通过e.message
和e.backtrace
获取有关错误的更多信息。也许像if e.message.include?("some string")
.
如果已确定存在错误的子类,则可以仅将rescue Oauth::Error
替换为子类。