[英]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; 我可以使用
ActiveRecord::StatementInvalid
从中解救出来,但这对我来说太通用了。 I would like to only rescue when the underlying error is PG::UndefinedTable
. 我只想在基本错误是
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. PS:我看到
error.cause
导致潜在的错误,但是我不确定这是否是“公共”接口,并且这是实现目标的一种简便的方法。
2018 Update: 2018年更新:
ex.original_exception
has been deprecated in favor of ex.cause
. 不推荐使用
ex.original_exception
,而推荐使用 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. ActiveRecord::StatementInvalid
是一种特殊的错误类型,在其中封装了其他错误。 You can access the original one with .original_exception
: 您可以使用
.original_exception
访问原始.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.