rescue_from考拉例外

时间:2011-12-20 03:46:38

标签: ruby ruby-on-rails-3 facebook-graph-api exception-handling koala

或许是初学者问题:

我正在尝试使用Koala检查来自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.):

我在这里缺少什么?

2 个答案:

答案 0 :(得分:8)

rescue_from不是像rescue那样的Ruby的语法结构 - 它是一个普通的函数,你需要一个块来使用它。在你的代码中,没有给出代码,rescue_from被执行并被有效地跳过 - 它之后的内容与之前引发的任何异常无关(就像你放置任何其他函数,如puts一样),而不是rescue_from)。

查看rescue_from使用here的示例。

要使此代码有效,您需要vanilla Ruby rescue

rescue Koala::Facebook::APIError => e

答案 1 :(得分: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
相关问题