这是一个真实的简单示例:
puts File.join(nil, "hello")
将输出
test.rb:4:in 'join': can't convert nil into String (TypeError)
from test.rb:4
但是当我这样做时:
begin
puts File.join(nil, "hello")
rescue => exception
puts exception.backtrace
end
这将输出
test.rb:4:in 'join'
test.rb:4
现在如何捕获完整的回溯,包括“不能将nil转换为String(TypeError)”部分?
@萨拉船:
在我的特定代码中,此代码段:
puts "=============================="
puts error.message
puts "=============================="
puts error.inspect
puts "=============================="
puts error.backtrace
puts "=============================="
退货
==============================
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
==============================
最佳答案
根据对#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是描述性部分:
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
因此,要获取所需的数据类型,可以执行以下操作:
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
关于ruby - Ruby救援以显示完整的回溯,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1466577/