Rails now uses error_highlight to locate the columns where an error is present

Ruby 3.1 introduced a new feature called error_highlight which allows you to pinpoint the exact column where an error is present.

Standard error messages in Rails show the row the error has occurred in. This is useful in most scenarios, however, for certain types of errors it can get less helpful.

For example, consider a hash of hashes. If accessing a key that does not exist, it can often be difficult to pinpoint the location where the key was accessed incorrectly.

Consider the below example,

  hash = { jane: { name: "Jane", age: "25", city: "NYC" }}

The above code will raise an error like,

  NoMethodError: undefined method `[]` for nil:NilClass

However, it does not say if the key :john is not present or if the hash itself doesn’t exist.


Despite Ruby 3.1 having the error_highlight feature, Rails did not use it. Even when the Rails app runs in a 3.1 environment!

However the Rails logs shows exactly where the error occurred.

NoMethodError (undefined method `[]' for nil:NilClass

app/controllers/application_controller.rb:4:in `home'


Thanks to this PR which brings in error_highlight (available since Ruby 3.1) directly on the Rails error page.

Error messages now display the fine-grained location of an error, not just a line number but also the column range of the erroneous code fragment.

The PR makes two significant changes,

  • Uses Exception#backtrace_locations (instead of Exception#backtrace) to extract the column information.
  • Use ErrorHighlight.spot to identify the column of the error.

Join Our Newsletter