views:

345

answers:

3

I'm having a problem right now where I can't see where my child threads are spitting out error messages which is making it difficult to debug.

eg:

Thread.new{
    a = 1/0
}

Is there any way to have all thread errors print out at stderr?

+3  A: 

Set the Thread class' abort_on_exception flag to true.

Alternately, wrap the thread body in a try/catch block and dump the exception in the catch.

Morendil
+1  A: 

This should catch any errors you don't explicitly handle and print them to STDOUT.

require 'pp'

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

result: #<ZeroDivisionError: divided by 0>

Lolindrath
+1  A: 

Set $DEBUG to true (you can do this from the command line with -d), and you'll get

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
Andrew Grimm