Best Practice: Try vs Rescue

前端 未结 3 931
清歌不尽
清歌不尽 2021-01-30 02:43

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

user.try(:email)

VS

user.email rescue nil
<         


        
3条回答
  •  温柔的废话
    2021-01-30 03:37

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

    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 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.

    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
    

提交回复
热议问题