本文介绍了最佳实践:尝试与救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is a best practice? To use try or use rescue?

user.try(:email)

VS

user.email rescue nil
post.try(:comments).try(:first).try(:author)

VS

post.comments.first.author rescue nil

使用这些有什么区别吗?

Is there any difference in using any of these?

推荐答案

尝试和救援服务于不同的目的.try 的目的是让您不必再做:

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

if user && user.email

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

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

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

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

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

这篇关于最佳实践:尝试与救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:06