从 Mysql2::Error 中拯救
我有一个简单的问题。我有一个连接表,它有一个索引,可确保 (col 1, col 2) 是唯一的。
我正在使用 mysql2 gem 添加到该表,并且如果尝试导致重复键错误,则尝试捕获 Mysql2::Error 。当我收到重复密钥错误时,我的救援主体没有被执行。
begin
self.foo << bar
rescue Mysql2::Error
logger.debug("#{$!}")
end
我在执行 self.foo << 时收到以下错误bar
Mysql2::Error:键“index_foos_bars_on_foo_id_and_bar_id”的重复条目“35455-6628”:插入foos_bars
(foo_id
,bar_id
) VALUES (35455, 6628)
但我的救援声明没有被击中!异常是没有被成功拯救出来的。我做错了什么?如果我删除 Mysql2::Error 并救援所有内容,那么它就可以工作。但这是不好的做法 - 我只想在出现重复条目时从 Mysql2::Error 中拯救出来。
谢谢,
I have a simple question. I have a join table which has an index that ensure that (col 1, col 2) is unique.
I am adding to that table using mysql2 gem and am trying to catch the Mysql2::Error if the attempt results in a duplicate key error. While I am getting the duplicate key error, my rescue body is not being executed.
begin
self.foo << bar
rescue Mysql2::Error
logger.debug("#{$!}")
end
I am receiving the following error upon executing self.foo << bar
Mysql2::Error: Duplicate entry '35455-6628' for key 'index_foos_bars_on_foo_id_and_bar_id': INSERT INTO foos_bars
(foo_id
, bar_id
) VALUES (35455, 6628)
BUT my rescue statement is not being hit! The exception is not be successfully rescued from. What am I doing wrong? If I remove Mysql2::Error and rescue for everything, then it works. But that is bad practice - I just want to rescue from Mysql2::Error which in the event of a duplicate entry.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mysql2::Error
现在被包装在另一个异常类中。将代码更改为:...您将看到需要救援的真正异常类。
编辑:在这种情况下,它似乎是
ActiveRecord::RecordNotUnique
Mysql2::Error
is wrapped in another exception class now. Change your code to:...and you'll see the real exception class that you need to rescue.
Edit: It seems in this case it turned out to be
ActiveRecord::RecordNotUnique