简体   繁体   English

Rails 2.3-在模型中处理ActiveRecord :: StatementInvalid

[英]Rails 2.3 - Handling ActiveRecord::StatementInvalid within the model

A model in my Rails application started throwing ActiveRecord::StatementInvalid with this message: "Mysql::Error: Deadlock found when trying to get lock; try restarting transaction ..." The way I handled this at first is wherever I have: 我的Rails应用程序中的模型开始抛出ActiveRecord :: StatementInvalid并显示以下消息:“ Mysql :: Error:尝试获取锁时发现了死锁;尝试重新启动事务...”无论如何,我最初的处理方式是:

myModel.update/save/update_all

I wrap it to catch that exception like: 我包装它来捕获该异常,例如:

begin
  myModel.update_all(..) 
rescue Exception => e
  if e.message.include?("Deadlock")
    retry
  end
end

The problem with this is that I have to rescue this exception everywhere I have an update/save and that I have to be careful that the retry does do things twice or even worse go into an infinite loop. 这样做的问题是,我必须在有更新/保存的所有地方都挽救该异常,并且必须小心,重试会做两次甚至更糟的事情,从而陷入无限循环。 Is the a way I can address this issue in one spot on the model level like in a callback for example? 我可以像在回调中那样在模型级别的一个位置上解决此问题的方法吗? It seems that an after_save or after_update won't do the trick since the exception wouldn't have been thrown at this point yet. 似乎after_save或after_update无法解决问题,因为此时尚未引发异常。 I'm in Rails 2.3.8 so an after_commit or after_rollback is not an option for me. 我在Rails 2.3.8中,因此after_commit或after_rollback对我来说不是一个选择。 Any ideas? 有任何想法吗? Thanks! 谢谢! ps: I know there are ways to avoid or reduce the chances of mysql getting a deadlock but I'm ok with just restarting the transaction after the deadlock happens since in my case the deadlock doesn't happen too often ps:我知道有一些方法可以避免或减少mysql出现死锁的机会,但是我可以在死锁发生后重新启动事务,因为在我看来,死锁不会经常发生

Maybe you can try a 'rescue_from' in your ApplicationController, like the following: 也许您可以在ApplicationController中尝试“ rescue_from”,如下所示:

class ApplicationController < ActionController::Base

    rescue_from ActiveRecord::StatementInvalid, :with => :my_custom_error_handler


    protected

    def my_custom_error_handler(exception)
      ...
    end
end

But I'm not sure if it will handle your retry properly. 但是我不确定它是否可以正确处理您的重试。 Worth a try. 值得一试。 Let me know! 让我知道!

我想我会和这个宝石一起解决死锁问题https://github.com/mperham/deadlock_retry

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

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