【问题标题】:Rake exception management耙异常管理
【发布时间】:2016-01-20 18:50:38
【问题描述】:

考虑这个 Rake 任务:

namespace :foo do
  task :bar do
    begin
      raise 'foo'
    rescue RuntimeError => ex
      raise ex.class, 'bar', ex.backtrace
    end
  end
end

结果如下:

rake aborted!
bar
/home/vagrant/proj/lib/tasks/foo.rake:52:in `block (2 levels) in <top (required)>'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `block in load'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
-e:1:in `<main>'
foo
/home/vagrant/proj/lib/tasks/foo.rake:52:in `block (2 levels) in <top (required)>'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `block in load'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'
/home/vagrant/.gem/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'
-e:1:in `<main>'
Tasks: TOP => foo:bar
(See full trace by running task with --trace)

如您所见,原始异常 (foo) 和新异常 (bar) 都有。 这是为什么?我本以为 foo 异常已被妥善救出,不会出现在这里。

【问题讨论】:

    标签: ruby-on-rails ruby rake rake-task


    【解决方案1】:

    原来的例外 (foo) 都不存在。

    瑞克文件:

    namespace :foo do
      task :bar do
        begin
          raise "message from foo"
        rescue RuntimeError => ex
          puts "#{ex.message}. foo is rescued"             # <= 1st
          raise ex.class, 'message from bar', ex.backtrace # <= 2nd
        end
      end
    end
    

    输出:

    message from foo. foo is rescued # <= 1st
    rake aborted!
    message from bar # <= 2nd
    /home/vagrant/Rakefile:4:in `block (2 levels) in <top (required)>'
    message from foo # <= from backtrace
    /home/vagrant/Rakefile:4:in `block (2 levels) in <top (required)>'
    Tasks: TOP => foo:bar
    (See full trace by running task with --trace)
    

    【讨论】:

    • 感谢您的回答@yhirano55。但是,恐怕我仍然不明白为什么第一个异常的消息会在回溯中?据我所知,这不是标准的 Ruby 行为?
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2015-03-10
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多