我正在编写一个脚本,用于从各种 url 收集数据。我想将 beginrescue
block 中的错误收集到一个数组中,以便在程序以详细模式运行时输出它们。正常使用时,失败的连接将被忽略,脚本将移至下一个 url。
我认为最好的方法是在脚本顶部创建一个数组 errArray = Array.new
来保存错误,然后执行以下操作:
rescue Exception => e
errArray << e.message
在各种函数中记录错误。 die
函数使用 p
输出数组,除非该数组为空。但是,我收到错误
Undefined local variable or method 'errArray'
任何帮助(和建设性批评)表示赞赏。
编辑:模具功能:
def die(e)
p errorArray unless errorArray.empty?
# Some other irrelevant code
end
最佳答案
errArray
不是全局变量,因此方法无法访问它。您可以通过$err_array
将其声明为全局变量。
但是最好的解决方案是创建一个简单的类:
class ExceptionCollector
def collect
yield
rescue => e
errors << e.message
end
def errors
@errors ||= []
end
end
然后简单:
$logger = ExceptionCollector.new
$logger.collect do
# this may raise an exception
end
def foo
$logger.collect do
# another exception
end
end
$logger.errors #=> list of errors
关于ruby - 收集 ruby 脚本中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19049821/