Ruby中的Rescue无法识别的变量

路易吉

我有以下代码:

  rescue Timeout::Error, StandardError => e
      puts "Caught exception: #{e.message}".red
      log.puts("#{e.backtrace}")
      email_ids_all.each do |email_delete|
        call= "/api/v2/emails/#{email_delete}/"
        ......

在这篇rescue文章之前,我已经定义了logemail_ids_all但是,在ruby脚本中都无法识别这些。如果我这样做:

 rescue Timeout::Error, StandardError => e
    File.open(rescuelogfile, 'w') do |log| #setup log to write response codes.
      puts "Caught exception: #{e.message}".red
      log.puts("#{e.backtrace}")
      email_ids_all.each do |email_delete|
        call= "/api/v2/emails/#{email_delete}/"
        ....

log工作正常,这是有道理的。重新定义email_ids_all救援模块中包含数组和其他变量将需要大量的编写工作。

无论如何,在救援过程中是否可以识别变量?基本上我的代码是这样布置的:

begin

#some code

rescue
  #above code

end

我正在使用ruby 1.9.3。

编辑 - -

log我的begin陈述后立即开始

begin
  File.open(logfile, 'w') do |log| #setup log to write response codes.

log.puts除了抛出错误时,它可以在整个代码中正常工作,然后在log无法使用的情况下运行救援脚本

同样的道理email_ids_all有一个API调用可生成大约10,000封电子邮件,并将每封电子邮件添加到数组中email_ids_all该脚本在生成这些电子邮件的过程中途收到错误消息,因此我需要救援脚本删除email_ids_all阵列中的所有电子邮件ID 但是无论出于何种原因,我都会收到以下错误消息:

FS_Test_Env.rb:762:in `block in <main>': undefined local variable or method `email_ids_all' for main:Object (NameError)
    from FS_Test_Env.rb:759:in `open'
    from FS_Test_Env.rb:759:in `rescue in <main>'
    from FS_Test_Env.rb:7:in `<main>'

有什么想法吗?

undur_gongor

块参数的范围log仅限于该块。这是openwith块的重点。

也许您想做:

begin
  log = File.open('logfile', 'w')
  ...
rescue
  ...
ensure
  log.close
end

请注意,这不包括打开日志文件时的错误。

关于email_ids_all,我猜(!)您在如下语句中有例外:

email_ids_all = ... a long and complex calculation which raises an exception

如果是,则问题是仅在计算了整个右侧之后才进行分配。email_ids_all发生异常时尚未创建var

为了访问在异常之前创建的元素,您必须跟踪它们,例如

begin
  email_ids = []
  10000.times do 
    email_ids << ... # create element eventually raising an exception
  end
rescue
  ... # treat the already created elements
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章