2016-01-20 51 views
0

考慮這個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例外已被妥善解救,不會在這裏出現。

回答

0

這裏不是最初的例外(foo)。

Rake文件:

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) 
+0

謝謝您的回答@ yhirano55。但是,我恐怕我仍然不明白爲什麼第一個異常的信息會在回溯中?據我所知,這不是標準的Ruby行爲? – user4867444