【问题标题】:Exception handling for twitter gem when tweet id NotFound推特 ID NotFound 时推特 gem 的异常处理
【发布时间】:2015-05-24 20:25:15
【问题描述】:

我对编写异常处理非常陌生,我不确定如何解决这种特殊处理。

我在我的表格中保存了多条推文,以缩短对 Twitter 的调用。我还允许用户通过我的应用程序收藏这些推文。

但是,如果该推文已被删除,则出现的错误是

(Twitter::Error::NotFound) — Error raised when tweet does not exist or has been deleted.

我想做的是,如果我收到该错误,我想从我的表中删除这条推文。

这是我的代码:

def favorite
  not_favorited = self.favorites.where(favorited: false)
  not_favorited_ids = not_favorited.map(&:id)
  tweet_ids = not_favorited.map(&:tweet_id)
  begin
    Favorite.where(id: not_favorited_ids).update_all(favorited: true) && self.twitter.favorite!(tweet_ids)
  rescue Twitter::Error::NotFound => e
    # if tweet is not found, then delete the tweet from the favorites
  rescue Twitter::Error::AlreadyFavorited => e

  rescue Twitter::Error::Unauthorized => e
    logger.error "Unauthorized access"
  rescue => e
  end
end

如您所见,我已经为 Error::NotFound 提供了救援,但我不确定如何编写一段代码来获取该特定 id 并继续删除它,然后再继续该过程。

【问题讨论】:

    标签: ruby-on-rails ruby twitter


    【解决方案1】:

    update_all 不会返回有关哪些记录已成功更新以及哪些记录引发错误的任何有意义的信息。

    由于您要为每个失败的更新处理失败,最好一次更新一条推文。

    代码将类似于以下内容:

    Favorite.where(id: not_favorited_ids).each do |tweet|
      begin
         Favorite.update(tweet.id, favorited: true)
         self.twitter.favorite!(tweet.id)
      rescue Twitter::Error::NotFound => e
         # if tweet is not found, then delete the tweet from the favorites using tweet.id
      end
    end
    

    重写favorite 方法逻辑以一次处理一条推文可能是个好主意。

    【讨论】:

      【解决方案2】:

      您不能取消收藏不存在的推文。对象不见了。当你 destroy_status 时,这条推文就消失了。没有什么不喜欢的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-23
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        • 2017-07-15
        • 2021-01-22
        • 1970-01-01
        • 2023-01-18
        相关资源
        最近更新 更多