gpt4 book ai didi

Ruby Rescue 显示完整的回溯

转载 作者:数据小太阳 更新时间:2023-10-29 06:32:05 32 4
gpt4 key购买 nike

这是一个简单的例子:

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 转换为字符串 (TypeError)”部分?

@Sarah Vessels:在我的特定代码中,这个片段:

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 Rescue 显示完整的回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1466577/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com