简体   繁体   中英

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?

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

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

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

Something like this should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM