我有一个模型Transaction
和一个方法external_evaluation
。 external_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
中,无论调用哪个迭代函数(each
,each_with_object
,each_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/