【问题标题】:Exception handling in ruby - Deep down or in the top layer?ruby 中的异常处理 - 深层还是顶层?
【发布时间】:2017-09-22 00:39:08
【问题描述】:

这里有两种处理异常的方法

第一

def prep_food
    get_veggies()
    get_fruits()
rescue Exception => e
    # => do some logging
    # => raise if necessary
end

def get_veggies()
    # gets veggies
end

def get_fruits()
    # gets fruits
end

第二

def prep_food
    get_veggies()
    get_fruits()
end

def get_veggies()
    # gets veggies
rescue Exception => e
    # => do some logging
    # => raise if necessary
end

def get_fruits()
    # gets fruits
rescue Exception => e
    # => do some logging
    # => raise if necessary
end

第一种方法在顶层处理异常,而第二种方法在深层处理。 两者有什么区别,程序员什么时候应该在它们之间进行选择?

【问题讨论】:

    标签: ruby exception refactoring dry


    【解决方案1】:

    我更喜欢将异常拯救为特定的(rescue FooException 而不是rescue Exception)并尽可能靠近可能引发它们的行(我的begin ... rescue 块通常只包含一行)。

    此外,我只从我能够并愿意处理的异常中解救。如果我不能“修复”异常,那么捕获它有什么意义?

    也就是说:我会选择你的第二个例子。如果我必须以相同的方式处理相同类型的异常,那么我会考虑引入一个采用块并进行错误处理的方法。比如:

    def get_veggies
      with_foo_error_handling do
        # gets veggies
      end
    end
    
    def get_fruits
      with_foo_error_handling do
        # gets fruits
      end
    end
    
    private
    
    def with_foo_error_handling
      begin
        yield
      rescue FooException => e
        # handle error
      end
    end
    

    【讨论】:

    • 如果我不能“修复”异常,那么捕获它有什么意义?我更喜欢自己捕获特定的异常。但在某些情况下,我会捕获所有异常并将其写入日志,然后再次引发。这只是一个示例,问题不是针对捕获特定异常,而是针对捕获异常的位置。
    • 同意:记录和重新引发可能是处理异常的有效方式。在某些特殊情况下,即使忽略也可以。这取决于...
    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多