0

我有以下代码:

  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

我正在使用红宝石 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>'

有什么想法吗?

4

2 回答 2

1

The way you put it, it should work, for example:

irb(main):001:0> begin
irb(main):002:1* x = 1
irb(main):003:1> x / 0
irb(main):004:1> rescue Exception => e
irb(main):005:1> p x
irb(main):006:1> end
1
=> 1

So it looks like the exception is thrown before your variables are defined.

于 2013-09-04T14:00:37.633 回答
0

块参数的范围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
于 2013-09-04T14:12:43.157 回答