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.

## Before

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 whether 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.

## After

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.

The ^^^^^^^^^^^^^ part specifies that .first was nil.

If we send the data as empty, the error highlight will point under .first as shown below:

### Custom Formatter

The gem provides us with a facility to add our formatter. We need to override the #message_for method and use assign it to ErrorHighlight.formatter=.

When we apply this formatter to our above example the error highlight, we use * instead of ^.

### Disable error_highlight

We can also disable the error highlight gem by passing --disable-error_highlight to the ruby command.

NOTE: error_highlight gem works only on MRI and requires Ruby 3.1 or later.