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

Sha*_*ese 12 ruby multithreading

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

例如:

Thread.new{
    a = 1/0
}
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以在stderr打印出所有线程错误?

Mor*_*dil 17

将Thread类' abort_on_exception标志设置为true.

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


And*_*imm 9

设置$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
Run Code Online (Sandbox Code Playgroud)


Lol*_*ath 6

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

require 'pp'

Thread.new {
  begin
    a = 1/0
  rescue
    pp $!
  end
}
Run Code Online (Sandbox Code Playgroud)

结果: #<ZeroDivisionError: divided by 0>