gpt4 book ai didi

ruby-on-rails - 这是错误处理反模式吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:39 25 4
gpt4 key购买 nike

一位同事最近告诉我这是一种反模式(record 是一个 ActiveRecord):

  begin
record.save!
do_something_else
rescue => e
puts "Unable to save"
end

...我应该这样做:

  if record.save
do_something_else
else
puts "Unable to save"
end

他的论点是我正在使用异常进行流量控制(我同意这是不好的),但我相信这是一种典型的错误处理模式。

想法?

最佳答案

这是一个反模式,因为有比运行 save! 更好的方法来检查记录的有效性(如果它无效则引发错误)。

这可能是您同事的意思:

  if record.save
do_something_else
else
puts record.errors.full_messages
end

你看,这里使用错误作为控制流没有任何好处,因为这样做的迂回方式较少。

您还可以独立于保存尝试运行验证。 errors.full_messages 数组(字符串)在调用 record.valid? 时填充。 record.save 在内部调用 record.valid?

if record.valid?
record.save # or save!; by this point you can assume the record is valid
else
puts record.errors.full_messages
end

关于ruby-on-rails - 这是错误处理反模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com