Ruby-on-rails 最佳实践:尝试与救援

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6063347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:11:03  来源:igfitidea点击:

Best Practice: Try vs Rescue

ruby-on-railsruby

提问by LuisVM

What is a best practice? To use tryor use rescue?

什么是最佳实践?使用try或使用rescue

user.try(:email)

VS

VS

user.email rescue nil


post.try(:comments).try(:first).try(:author)

VS

VS

post.comments.first.author rescue nil

Is there any difference in using any of these?

使用这些有什么区别吗?

回答by Hyman Chu

Try and rescue serve different purposes. The purpose of tryis to save you from having to do:

尝试和救援服务于不同的目的。的目的try是让您免于执行以下操作:

if user && user.email

Or any situation where the parent object can possibly be nil, which would cause a NoMethodError on NilClass. The purpose of rescueis to handle exceptions that get thrown by your method invocation. If you expect an exception from calling user.email, then you can rescue nilit to prevent the exception from bubbling up.

或者父对象可能为 nil 的任何情况,这将导致 NilClass 上的 NoMethodError。的目的rescue是处理方法调用引发的异常。如果您希望调用 出现异常user.email,那么您可以使用rescue nil它来防止异常冒泡。

In general, I'd say avoid using rescue nilunless you know explicitly what exceptions you are rescuing because you could be rescuing a different exception, and you would never know it because rescue nilwould prevent you from seeing it. At the very least maybe you could log it:

一般来说,我会说避免使用,rescue nil除非你明确知道你正在拯救什么异常,因为你可能正在拯救一个不同的异常,你永远不会知道它,因为rescue nil会阻止你看到它。至少也许你可以记录它:

begin
  ...some code...
rescue => ex
  logger.error ex.message
end

回答by Adam Byrtek

Both seem fishy and can mask other bugs. Are you sure you really want to get nil there? Maybe it would be better to check whether there are any comments first, and cover the empty case explicitly?

两者都看起来很可疑,并且可以掩盖其他错误。你确定你真的想在那里得到零吗?也许最好先检查是否有任何评论,并明确覆盖空案例?

回答by Jonathan_W

Nothing is Somethingis an excellent talk by Sandi Metz that helps understand why @AdamByrtek is spot on, and why we should all be marking the failed cases in a smarter, more object-oriented way that x ? y : nil

没有什么是 Sandi Metz 的精彩演讲,有助于理解为什么 @AdamByrtek 出现在现场,以及为什么我们都应该以更智能、更面向对象的方式标记失败的案例x ? y : nil