3

也许初学者的问题:rescue_from考拉例外

我试图检查我的用户从Facebook与考拉的权限。在某些情况下,我会得到一个错误。所以我只想抓住它并重定向到重新认证。

def check_facebook_permissions 
    if token = current_user.try(:authentications).find_by_provider('facebook').try(:token) 
     graph = Koala::Facebook::API.new(token) 
     permissions = graph.get_connections('me','permissions') 
     session[:facebook] = {} 
     session[:facebook][:ask_publish_actions] = true if permissions[0]['publish_actions'] != true && permissions[0]['publish_stream'] != true 
    end 
    rescue_from Koala::Facebook::APIError 
    # Do something funky here 
    end 

我以为这很直接,但我从来没有打我救。相反,我得到:

Koala::Facebook::APIError (OAuthException: Error validating access token: Session has expired at unix time 1324026000. The current unix time is 1324352685.): 

我在这里错过了什么?

回答

8

rescue_from不是Ruby的语法结构,比如rescue是 - 它是一个正常的函数,并且您需要一个块来处理它。在你的代码中,没有给出任何代码,rescue_from得到执行并且被有效地跳过 - 在它之前引发的任何异常没有影响之后(就像你使用其他函数,如puts而不是rescue_from)。

查看rescue_from的示例使用here

为了使此代码工作,你需要的香草红宝石rescue

rescue Koala::Facebook::APIError => e 
+0

AAAAA ......这是我的命。谢谢! – TLK 2011-12-20 04:22:05

0

使用Ruby处理错误正确的语法是:

begin 
    # do something that will throw an error 
rescue StandardError => e # StandardError is the root class of most errors 
    # rescue the error 
end 
+1

如果存在其他分隔符,则不需要'begin';在这种情况下,'def'就足够了。当您想要将可挽救部分限制在一个尚未处于“xxxx ... end”结构中的语法区域时,使用“begin”。 – Amadan 2011-12-20 03:54:47