2017-01-11 51 views
0

我使用的OAuth2,使按以下格式要求:只有营救具体的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

回答

1

我不知道或者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替换为仅有子类。