![](/img/trans.png)
[英]ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: in rails query
[英]Rescue PG::UndefinedTable instead of ActiveRecord::StatementInvalid
例如,如果我嘗試刪除一個不存在的表,則會收到以下錯誤:
"#<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation \"aiurea\" does not exist\n
我可以使用ActiveRecord::StatementInvalid
從中解救出來,但這對我來說太通用了。 我只想在基本錯誤是PG::UndefinedTable
時進行救援。 我怎樣才能做到這一點?
PS:我看到error.cause
導致潛在的錯誤,但是我不確定這是否是“公共”接口,並且這是實現目標的一種簡便的方法。
ActiveRecord::StatementInvalid
是一種特殊的錯誤類型,在其中封裝了其他錯誤。 您可以使用.original_exception
訪問原始.original_exception
:
rescue ActiveRecord::StatementInvalid => ex
ex.original_exception # this will return the `PG::UndefinedTable` class, which you can further inspect.
end
更好的方法是:
rescue ActiveRecord::StatementInvalid => ex
if ex.original_exception.is_a?(PG::UndefinedTable)
# do something
else
raise ex
end
end
這樣的事情應該工作
rescue ActiveRecord::StatementInvalid => ex
if ex.message =~ /PG::UndefinedTable/
// Do stuff here
else
raise ex
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.