ruby-on-rails - 如何为产生可迭代的函数添加默认错误处理?

标签 ruby-on-rails ruby activerecord error-handling

我有一个模型Transaction和一个方法external_evaluationexternal_evaluation在堆栈中向下移动,并最终调用AWS Lambda。如果响应不正确,则会引发BadResponse异常。

代码库中有一种经常使用的模式,例如

def get_some_transactions() 
  Transaction.where(some_column: some_expression)
end

def do_some_stuff()
  get_some_transactions.each do |transaction|
    do_something(transaction.external_evaluation)
  rescue BadResponse => e
    log(e)
    next
  end
end

def do_some_other_stuff()
  get_some_transactions.each_with_object({}) do |transaction, transaction_hash|
    transaction_hash[transaction] = do_something_else(transaction.external_evaluation)
  rescue BadResponse => e
    log(e)
    next
  end
end

我真的不喜欢这种模式中错误处理代码的重复,并且希望能够将默认错误处理添加到get_some_transactions中,无论调用哪个迭代函数(eacheach_with_objecteach_with_index,...),该默认错误处理都将适用。在Ruby中有惯用的方法吗?

最佳答案

def with_error_handing(&block)
  begin
    yield
  rescue BadResponse => e
    log(e)
  end
end

def do_some_stuff()
  get_some_transactions.each do |transaction|
    with_error_handing do
      do_something(transaction.external_evaluation)
    end
  end
end

def do_some_other_stuff()
  get_some_transactions.each_with_object({}) do |transaction, transaction_hash|
    with_error_handing do
      transaction_hash[transaction] = do_something_else(transaction.external_evaluation)
    end
  end
end

关于ruby-on-rails - 如何为产生可迭代的函数添加默认错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625343/

相关文章:

ruby-on-rails - 如何使用 has_and_belongs_to_many 为数据库做种

ruby-on-rails - 如何在 Rails 中处理 YouTube 的缩略图?

ruby-on-rails - 如何通过 Ruby Gem 共享 activerecord 模型

ruby-on-rails - has_many 关系中的 Active Record 对象何时保存?

ruby-on-rails - 如何使用 JSON 的 Nokogiri 中的 XPath 从 eBay 和亚马逊抓取图像

ruby - 需要一个 Ruby 方法来确定矩阵 "touching"另一个元素的元素

javascript - react : How to Read a PNG in the client/browser and parse it to PNGJS

ruby - 用 ruby​​ 写了 TicTacToe,电脑玩的不爽

ruby-on-rails - 搜索 has_and_belongs_to_many :tags 的模型

ruby-on-rails - ruby rails : Passing argument to singleton