如何从ruby线程获取错误消息

我现在遇到了一个问题,我无法看到我的子线程在哪里吐出错误消息,这使得调试变得困难。

例如:

Thread.new{ a = 1/0 } 

有什么方法可以在stderr打印出所有线程错误吗?

将Thread类的abort_on_exception标志设置为true。

或者,将线程主体包装在throw / catch块中,并将exception转储到catch中。

$DEBUG设置$DEBUG true(您可以使用-d从命令行执行此操作),您将获得

 ruby -d bad_thread.rb Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems.rb:1113 - no such file to load -- rubygems/defaults/operating_system Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems/config_file.rb:34 - no such file to load -- Win32API Exception `ZeroDivisionError' at bad_thread.rb:2 - divided by 0 bad_thread.rb:2:in `/': divided by 0 (ZeroDivisionError) from bad_thread.rb:2 from bad_thread.rb:1:in `initialize' from bad_thread.rb:1:in `new' from bad_thread.rb:1 

这应该捕获您没有明确处理的任何错误并将它们打印到STDOUT。

 require 'pp' Thread.new { begin a = 1/0 rescue pp $! end } 

结果: #