我想使用Ruby Core的超时时间来超时查询ActiverEcord查询,但是ActivereCord似乎正在捕获Timeout::Error
并将其包裹在ActiveRecord::StatementInvalid
例外。
> Timeout::timeout(3) { sleep 4000 }
Timeout::Error: execution expired
...
> Timeout::timeout(3) { ActiveRecord::Base.connection.execute "select pg_sleep(4)"}
(3001.5ms) select pg_sleep(4)
: execution expired: select pg_sleep(4)
ActiveRecord::StatementInvalid: : execution expired: select pg_sleep(4)
...
这是不幸的,因为我也想捕获生成ActiveRecord::StatementInvalid
例外的真实SQL错误并以不同的方式对待它们。有没有办法区分两者?(比匹配"执行过期"的异常消息更清洁)。
尝试使用此代码:
begin
Timeout::timeout(3) do
begin
ActiveRecord::Base.connection.execute "select pg_sleep(4)"
rescue ActiveRecord::StatementInvalid
# handle ActiveRecord::StatementInvalid exception
end
end
rescue Timeout::Error
# handle Timeout::Error exception
end
如果要回收超时::错误,则应在超时块中捕获所有其他例外。