When working with any programming language, developers deal with error stack traces whenever an exception or an error gets raised. The stack trace gracefully points out the error location and provides information about program subroutines.
When it comes to Ruby, we are aware of the different errors and exceptions raised. Let’s check an example for the same.
As seen in the above example, IRB pointed out the line number where the error occurred.
The above error was pretty easy to identify and fix since the input was incorrect. Let’s take an example where we want to parse some API response and fetch user data from the nested JSON object.
The error raised
undefined method  for nil:NilClass does not point out
data[:result] is nil or
data[:result].first is nil.
For more complex and nested JSON responses, it becomes difficult to identify which param is nil.
Ruby 3.1 ships with error_highlight gem and will be required when a Ruby process starts up. We don’t have to add any explicit setup configuration for setting up this gem.
When we execute the above code using Ruby 3.1.0, we can see at which point the data was nil.
^^^^^^^^^^^^^ part specifies that
.first was nil.
If we send the
data as empty, the error highlight will point under
.first as shown below:
The gem provides us with a facility to add our formatter.
We need to override the
use assign it to
When we apply this formatter to our above example
the error highlight, we use
* instead of
We can also disable the error highlight gem by passing
--disable-error_highlight to the
NOTE: error_highlight gem works only on MRI and requires Ruby 3.1 or later.