在我的 Controller 中,我的代码如下所示:
@mymodel.transaction do
for a in arr
@mymodel.some_method(a)
end
end
在@mymodel#some_method 中我可以抛出一个 ActiveRecord::Rollback
异常,它在数据库中执行它需要做的事情,但是我只是得到一个 HTTP 500 并且无法捕获异常以优雅的方式让用户知道哪里出了问题。
我试过将 @mymodel.transaction do 包装在开始/救援 block 中,但这也行不通。捕获异常以便我可以向用户呈现正确 View 的最佳方法是什么?
最佳答案
来自 ActiveRecord::Base
文档:
Normally, raising an exception will cause the
transaction
method to rollback the database transaction and pass on the exception. But if you raise an ActiveRecord::Rollback exception, then the database transaction will be rolled back, without passing on the exception.
一个小例子:
class ThrowController < ApplicationController
def index
status = ActiveRecord::Base.connection.transaction do
raise ActiveRecord::Rollback.new
end
Rails.logger.info "followed transaction"
end
end
然后:
>> c = ThrowController.new.index
=> "followed transaction \n"
如您所见,ActiveRecord:::Rollback
异常被 transaction
block 吞没。
在我看来,您的代码正在发生我们不知道的其他事情。
关于ruby-on-rails - Ruby on Rails:如何捕获 ActiveRecord::Rollback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693501/