【问题标题】:rescue_from Koala exceptionsrescue_from Koala 异常
【发布时间】:2012-01-24 03:03:48
【问题描述】:

也许是初学者的问题:

我正在尝试使用 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.):

我在这里错过了什么?

【问题讨论】:

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


    【解决方案1】:

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

    查看rescue_from 使用here 的示例。

    要使这段代码正常工作,您需要原版 Ruby rescue

    rescue Koala::Facebook::APIError => e
    

    【讨论】:

    • aaaaa ......那真是要了我的命。谢谢!
    【解决方案2】:

    在 Ruby 中处理错误的正确语法是:

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

    【讨论】:

    • begin 如果存在其他分隔符,则不需要;在这种情况下,def 就足够了。 begin 用于将可恢复部分限制为尚未在 xxxx ... end 构造中的句法区域。
    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2011-07-12
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多