Ruby 2.6为Exception#full_message增加了选项

96 阅读1分钟

Ruby 2.6为Exception#full_message增加了选项

Ruby 2.5.0

Exception#full_message方法返回一个格式化的异常字符串:

>> e = StandardError.new('foo')
=> #<StandardError: foo>
>> e.full_message
=> "\e[1mTraceback\e[m (most recent call last):\n(irb):14:in `full_message': \e[1mfoo (\e[1;4mStandardError\e[m\e[1m)\e[m\n"

这个字符串也包含转义序列。

有人提议,转义序列应该从错误信息中排除。

Nobuyoshi Nakada说,由于Exception#full_message被期望返回打印到stderr的信息,转义序列是故意的。

Benoit Daloze建议,我们可以提供一个选项来禁用转义序列,并得到了批准。

Ruby 2.6.0

Ruby 2.6.0为Exception#full_message方法提供了highlight 选项来排除转义序列:

>> e = StandardError.new('foo')
=> #<StandardError: foo>
>> e.full_message
=> "\e[1mTraceback\e[m (most recent call last):\n(irb):11:in `full_message': \e[1mfoo (\e[1;4mStandardError\e[m\e[1m)\e[m\n"
>> e.full_message(highlight: false)
=> "Traceback (most recent call last):\n(irb):12:in `full_message': foo (StandardError)\n"

order 参数提供了将错误信息和最里面的回溯放在Exception#full_message返回结果的顶部或底部的选项。order 的值必须是:top:bottom

>> e = StandardError.new('foo')
=> #<StandardError: foo>
>> e.full_message
=> "\e[1mTraceback\e[m (most recent call last):\n(irb):2:in `full_message': \e[1mfoo (\e[1;4mStandardError\e[m\e[1m)\e[m\n"
>> e.full_message(highlight: false)
=> "Traceback (most recent call last):\n(irb):3:in `full_message': foo (StandardError)\n"
>> e.full_message(highlight: false, order: :top)
=> "(irb):4:in `full_message': foo (StandardError)\n"
>> e.full_message(highlight: false, order: :bottom)
=> "Traceback (most recent call last):\n(irb):5:in `full_message': foo (StandardError)\n"

让我们为一个错误对象设置一个回溯,并为Exception#full_message方法尝试命令选项:

>> e = StandardError.new('foo')
=> #<StandardError: foo>
>> e.set_backtrace(["a.rb:1", "b.rb:2"])
=> ["a.rb:1", "b.rb:2"]
>> e.full_message(highlight: false, order: :top)
=> "a.rb:1: foo (StandardError)\n\tfrom b.rb:2\n"
>> e.full_message(highlight: false, order: :bottom)
=> "Traceback (most recent call last):\n\t1: from b.rb:2\na.rb:1: foo (StandardError)\n"

希望你使用这些选项和Exception#full_message来调试ruby应用程序。