Ruby 异常处理
我想添加一个异常处理程序。在一个类中,我有很多方法,我想在所有这些方法中添加Ruby 异常处理,ruby,exception-handling,Ruby,Exception Handling,我想添加一个异常处理程序。在一个类中,我有很多方法,我想在所有这些方法中添加begin-rescue-end。我可以在一个地方定义它,而不是在所有方法中添加begin-rescue-end 您可以将错误处理提取到一个方法中,并从所有其他方法调用它 class Foo def method1 with_exception_handling do raise 'some error' end end def method2 with_exceptio
begin-rescue-end
。我可以在一个地方定义它,而不是在所有方法中添加begin-rescue-end
您可以将错误处理提取到一个方法中,并从所有其他方法调用它
class Foo
def method1
with_exception_handling do
raise 'some error'
end
end
def method2
with_exception_handling do
puts "normal execution"
end
end
private
def with_exception_handling(&block)
begin
block.call
rescue => ex
puts "caught exception: #{ex.message}"
end
end
end
f = Foo.new
f.method1
f.method2
# >> caught exception: some error
# >> normal execution
我认为一般来说,拥有如此广泛的异常处理不是一个好主意,因为它增加了难以检测的bug从测试和错误日志中溜走的可能性。但是,如果您有一个非常好的用例,您可以使用
method\u missing
创建一种优雅的方法来拯救每个方法,而不必更改每个方法中的代码
如果你的方法是
my_object.my_method
您可以使用方法\u missing
来允许以下语法:
my_object.my_method_rescued
例如,将\u
附加到任何方法名称将执行错误处理程序中包装的方法
这是一个非常粗略的例子,但它应该给你一个想法:
class MyClass
def my_method
raise 'error!!!'
end
def method_missing(method_name, *args)
if method_name.to_s.end_with? '_rescued'
rescue_wrapper(method_name[0..-9], *args)
end
end
private
def rescue_wrapper(method_name, *args)
begin
self.send(method_name, *args)
rescue => e
# Error handling code here...
end
end
end
my_object = MyClass.new
my_object.my_method_rescued # => Calls error handling code on error
my_ojbect.my_method # => Raises an exception on error
您的情况还不够清楚。在调用情况下处理是相同的?或者可以使用一些元编程来包装带有错误处理的方法。