Ruby 3.1 ships with error highlight gem to better pinpoint the error in the code. It highlights the error in the code and provides the line number of the error.
Make sure to have Ruby 3.1.0 installed to try out this feature.
Let's take an example.
# test.rb
puts "Hello, calling invalid method: #{ invalid_method_name } here."
Now, if we run the above code, we will get an error as given below.
test.rb:1:in `<main>': undefined local variable or method `invalid_method_name' for main:Object (NameError)
puts "Hello, calling invalid method: #{ invalid_method_name } here."
^^^^^^^^^^^^^^^^^^^
As we can see, the error shown is highlighted in the code using ^^^^^^^^^^^^^^^^^^^
syntax. The tries to pin point the exact error location.
Let's take another example:
# test.rb
hash = {
title: "Ruby 3.1 ships with error highlight gem",
author: nil
}
puts hash[:authors][:name]
Now, let's run the above code.
ruby test.rb
This will give us the following error.
test.rb:6:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
puts hash[:authors][:name]
^^^^^^^
As we can see this error points at hash access for the name key. hash[:authors] is nil. Thus, it accurately highlights exact error location.
Disable error highlight
To disable error highlight, --disable-error_highlight argument can be passed to ruby command.
ruby --disable-error_highlight test.rb
Get metadata of the error
Error highlight gem provides the metadata of the error using ErrorHighlight.spot method. It can be used to enhance the error message along with custom formatter.
# test.rb
class TestSpot
def test_metadata
node = RubyVM::AbstractSyntaxTree.of(caller_locations.first, keep_script_lines: true)
ErrorHighlight.spot(node)
end
end
pp TestSpot.new.test_metadata
Now, let's run this file to see the output of ErrorHighlight.spot.
ruby test.rb
This gives us the following output.
{:first_lineno=>9,
:first_column=>15,
:last_lineno=>9,
:last_column=>29,
:snippet=>"pp TestSpot.new.test_metadata\n"}
- first_lineno and first_column keys shows the line number and column number of the error.
- last_lineno and last_column keys shows the last line number and column number of the error.
- snippet key shows the code snippet where the error is originated.
A custom formatter can be written using this information/metadata.