【问题标题】:Continuing loop through ResourceNotFound?继续循环通过 ResourceNotFound?
【发布时间】:2012-08-09 19:43:48
【问题描述】:

我正在循环访问一组用户,作为其中的一部分,我正在调用第三方 API(通过 Intercom API Ruby wrapper)。

如果找不到用户,Intercom API 会抛出 Intercom::ResourceNotFound,这会停止整个过程。

我只想让它在找不到用户时跳过它。

User.each do |user|
    user = Intercom::User.find_by_email(user.email) # Intercom::ResourceNotFound thrown if not found
    user.custom_data["Example"] = true
    user.save
end

这是 Intercom Ruby 包装器的问题吗?或者有没有典型的 Ruby 或 Rails 方式来处理这类事情?

【问题讨论】:

    标签: ruby-on-rails ruby api activeresource


    【解决方案1】:

    捕获异常怎么样?

    User.each do |user|
      begin
       user = Intercom::User.find_by_email(user.email) # Intercom::ResourceNotFound thrown if not found
       user.custom_data["Example"] = true
       user.save
      rescue Intercom::ResourceNotFound
      end
    end
    

    由于您只想跳过该用户(如果找不到)(并引发异常),因此在rescue 之后没有错误处理代码。但是如果你想放一些调试信息或类似的东西,你可以写:

      rescue Intercom::Resource
        puts %{Could not work on user...}
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2023-03-12
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多