简体   繁体   English

Ruby on Rails:我如何捕获ActiveRecord :: Rollback?

[英]Ruby on Rails: how do I catch ActiveRecord::Rollback?

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. 在@ mymodel#some_method我可以抛出一个ActiveRecord::Rollback异常,它在db中做它需要做的事情,但是我只是得到一个HTTP 500并且无法捕获异常以让用户以优雅的方式知道什么出错。

I've tried wrapping @mymodel.transaction do in a begin/rescue block, but that won't do it either. 我试过在开始/救援块中包装@ mymodel.transaction do,但是也不会这样做。 What's the best way to catch the exception so I can present the proper view to the user? 捕获异常的最佳方法是什么,以便为用户提供正确的视图?

From the ActiveRecord::Base documentation: ActiveRecord::Base文档:

Normally, raising an exception will cause the transaction method to rollback the database transaction and pass on the exception. 通常,引发异常将导致transaction方法回滚数据库事务传递异常。 But if you raise an ActiveRecord::Rollback exception, then the database transaction will be rolled back, without passing on the exception. 但是,如果引发ActiveRecord :: Rollback异常,则将回滚数据库事务,而不传递异常。

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. 如您所见, transaction块吞下了ActiveRecord:::Rollback异常。

It seems to me that something else is going on with your code that we're not aware of. 在我看来,我们还没有意识到你的代码正在发生的其他事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM