In my controller, I have code that looks like the following:
@mymodel.transaction do
for a in arr
@mymodel.some_method(a)
end
end
in @mymodel#some_method I could throw an ActiveRecord::Rollback
exception which in the db does what it needs to do, however I then simply get an HTTP 500 and no way to catch the exception to let the user know in an elegant way what went wrong.
I've tried wrapping @mymodel.transaction do in a begin/rescue block, but that won't do it either. What's the best way to catch the exception so I can present the proper view to the user?
From the ActiveRecord::Base
documentation:
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.
A small example:
class ThrowController < ApplicationController
def index
status = ActiveRecord::Base.connection.transaction do
raise ActiveRecord::Rollback.new
end
Rails.logger.info "followed transaction"
end
end
then:
>> c = ThrowController.new.index
=> "followed transaction \n"
As you can see, the ActiveRecord:::Rollback
exception is swallowed by the transaction
block.
It seems to me that something else is going on with your code that we're not aware of.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.