linkyndy
linkyndy

Reputation: 17928

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.

Upvotes: 7

Views: 1551

Answers (3)

benterprise
benterprise

Reputation: 106

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

Upvotes: 7

Gabriel Mazetto
Gabriel Mazetto

Reputation: 1130

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

Upvotes: 2

R&#233;mi Delhaye
R&#233;mi Delhaye

Reputation: 824

Something like this should work

rescue  ActiveRecord::StatementInvalid => ex
  if ex.message =~ /PG::UndefinedTable/
    // Do stuff here
  else
    raise ex
  end
end

Upvotes: 0

Related Questions