RyanScottLewis RyanScottLewis - 2 months ago 12
Ruby Question

Ruby Rescue To Display Full Backtrace

Here's a real quick example:

puts File.join(nil, "hello")


Would output

test.rb:4:in 'join': can't convert nil into String (TypeError)
from test.rb:4


But when I do this:

begin
puts File.join(nil, "hello")
rescue => exception
puts exception.backtrace
end


This will output

test.rb:4:in 'join'
test.rb:4


Now how do I capture the full backtrace, including the "can't convert nil into String (TypeError)" part?

@Sarah Vessels:
In my specific code, this snippet:

puts "=============================="
puts error.message
puts "=============================="
puts error.inspect
puts "=============================="
puts error.backtrace
puts "=============================="


returns

==============================
exit
==============================
#<SystemExit: exit>
==============================
/usr/lib/ruby/1.8/glib2.rb:37:in `exit'
/usr/lib/ruby/1.8/glib2.rb:37:in `exit_application'
multi.rb:234:in `main'
multi.rb:347
==============================

Answer

The value is stored there somewhere, based on this call to #inspect:

irb(main):001:0> begin
irb(main):002:1* puts File.join(nil, "Hello")
irb(main):003:1> rescue => exception
irb(main):004:1> puts exception.inspect
irb(main):005:1> end
#<TypeError: can't convert nil into String>
=> nil

Exception#message is the descriptive part:

irb(main):006:0> begin
irb(main):007:1* puts File.join(nil, "hello")
irb(main):008:1> rescue => ex
irb(main):009:1> puts ex.message
irb(main):010:1> end
can't convert nil into String
=> nil

So to get the type of data you're looking for, you could do something like the following:

irb(main):015:0> begin
irb(main):016:1* puts File.join(nil, "hey")
irb(main):017:1> rescue => ex
irb(main):018:1> puts "#{ex.backtrace}: #{ex.message} (#{ex.class})"
irb(main):019:1> end
(irb):16:in `join'(irb):16:in `irb_binding'C:/Ruby/lib/ruby/1.8/irb/workspace.rb
:52:in `irb_binding':0: can't convert nil into String (TypeError)
=> nil