Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescue PG::UndefinedTable instead of ActiveRecord::StatementInvalid

If I try to, for example, drop a table that doesn't exist, I will get the following error:

"#<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation \"aiurea\" does not exist\n

I can rescue from it using ActiveRecord::StatementInvalid, but it's too generic for me; I would like to only rescue when the underlying error is PG::UndefinedTable. How can I do this?

P.S.: I saw error.cause to lead to the underlying error, but I'm not sure whether this is "public" interface and it is an unobtrusive way to get to it.

like image 590
linkyndy Avatar asked Jan 08 '16 09:01

linkyndy


2 Answers

2018 Update:

ex.original_exception has been deprecated in favor of ex.cause. This worked for me:

rescue ActiveRecord::StatementInvalid => ex
  if ex.cause.is_a?(PG::UndefinedTable)
    # do something
  else
    raise ex
  end
end
like image 121
benterprise Avatar answered Nov 15 '22 05:11

benterprise


ActiveRecord::StatementInvalid is a special Error type that encapsulates other errors in it. You can access the original one with .original_exception:

rescue  ActiveRecord::StatementInvalid => ex
  ex.original_exception # this will return the `PG::UndefinedTable` class, which you can further inspect.
end

Better way to do is:

rescue ActiveRecord::StatementInvalid => ex
  if ex.original_exception.is_a?(PG::UndefinedTable)
    # do something
  else
    raise ex
  end
end
like image 40
Gabriel Mazetto Avatar answered Nov 15 '22 04:11

Gabriel Mazetto