Search code examples
ruby-on-railsexceptionmysql2

rescuing from 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,


Solution

  • Mysql2::Error is wrapped in another exception class now. Change your code to:

    begin
      self.foo << bar
    rescue Exception => e      # only for debug purposes, don't rescue Exception in real code
      logger.debug "#{e.class}"
    end
    

    ...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