仅救援特定的 OAuth2 错误

  • 本文关键字:OAuth2 错误 ruby oauth
  • 更新时间 :
  • 英文 :


我正在使用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.messagee.backtrace获取有关错误的更多信息。也许像if e.message.include?("some string").

如果已确定存在错误的子类,则可以仅将rescue Oauth::Error替换为子类。

最新更新