我正在编写一个脚本,从不同的url收集数据。我想将begin rescue块中的错误收集到一个数组中,以便在程序以详细模式运行时输出它们。正常使用时,会忽略一个失败的连接,脚本会转到下一个url。
我认为最好的方法是在脚本顶部创建一个数组来保存错误,然后:

rescue Exception => e
  errArray << e.message

在各种函数中记录错误。errArray = Array.new函数使用die输出数组,除非它是空的。但是,我得到了错误
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

09-30 17:42
查看更多