der*_*use 18 ruby-on-rails exception mysql2
我有一个简单的问题.我有一个连接表,其索引确保(col 1,col 2)是唯一的.
我使用mysql2 gem添加到该表,并尝试捕获Mysql2 :: Error,如果尝试导致重复键错误.当我收到重复键错误时,我的救援主体没有被执行.
begin
self.foo << bar
rescue Mysql2::Error
logger.debug("#{$!}")
end
Run Code Online (Sandbox Code Playgroud)
执行时我收到以下错误 self.foo << bar
Mysql2 ::错误:键'index_foos_bars_on_foo_id_and_bar_id'的重复条目'35455-6628':INSERT INTO foos_bars
(foo_id
,bar_id
)VALUES(35455,6628)
但我的救援声明没有被击中!该例外未能成功获救.我究竟做错了什么?如果我删除Mysql2 :: Error并为所有事情进行救援,那么它可行.但这是不好的做法 - 我只是想在重复输入的情况下从Mysql2 :: Error中解救出来.
谢谢,
sma*_*thy 22
Mysql2::Error
现在包装在另一个异常类中.将您的代码更改为:
begin
self.foo << bar
rescue Exception => e # only for debug purposes, don't rescue Exception in real code
logger.debug "#{e.class}"
end
Run Code Online (Sandbox Code Playgroud)
......你会看到你需要救援的真正的例外类.
编辑:在这种情况下似乎结果是ActiveRecord::RecordNotUnique
归档时间: |
|
查看次数: |
10338 次 |
最近记录: |