Ruby 2.6 added options to Exception#full_message

Written by Atul Bhosale on July 30, 2018; tagged under ruby

Ruby 2.6.0-preview2 was recently released.

Ruby 2.5.0

The Exception#full_message method returns a formatted string of the exception.

>> 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"

The string contains escape sequences too.

It was proposed that escape sequences should be excluded from the error message.

Nobuyoshi Nakada said that since Exception#full_message is expected to return the message printed to stderr, escape sequences are intentional.

Benoit Daloze suggested that we can provide an option to disable escape sequences and it was approved.

Ruby 2.6.0

Ruby 2.6.0 provides highlight option to the Exception#full_message method to exclude escape sequences.

>> 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"

The order argument provides options to place the error message and the innermost backtrace come at the top or the bottom of the result returned by Exception#full_message. The order value must be either :top or :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"

Let’s set a backtrace for an error object and try order option for Exception#full_message method.

>> 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"

Hope you use these options with Exception#full_message to debug ruby applications.

Here is the relevant commit and discussion.

If you have any questions or feedback, feel free to drop us a mail at team@codemancers.com.