Friday, May 3, 2024
HomeRuby On RailsRails now makes use of error_highlight to find the columns the place...

Rails now makes use of error_highlight to find the columns the place an error is current


Ruby 3.1 launched a brand new function
referred to as error_highlight which lets you pinpoint the precise column the place an error is current.

Customary error messages in Rails present the row the error has occurred in.
That is helpful in most situations, nevertheless,
for sure sorts of errors it could get much less useful.

For instance, think about a hash of hashes.
If accessing a key that doesn’t exist,
it could usually be troublesome to pinpoint the situation the place the important thing was accessed incorrectly.

Think about the under instance,

  hash = { jane: { identify: "Jane", age: "25", metropolis: "NYC" }}
  hash[:john][:age]

The above code will increase an error like,

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

Nonetheless, it doesn’t say if the important thing :john
will not be current
or if the hash itself doesn’t exist.

Earlier than

Regardless of Ruby 3.1 having the error_highlight function,
Rails didn’t use it.
Even when the Rails app runs in a 3.1 setting!

Nonetheless the Rails logs exhibits precisely the place the error occurred.

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

    hash[:john][:age]
               ^^^^^^):
app/controllers/application_controller.rb:4:in `dwelling'

After

Due to this PR
which brings in error_highlight (accessible since Ruby 3.1) straight on the Rails error web page.

Error messages now show the fine-grained location of an error,
not only a line quantity but additionally the column vary of the inaccurate code fragment.

The PR makes two vital adjustments,

  • Makes use of Exception#backtrace_locations (as a substitute of Exception#backtrace) to extract the column info.
  • Use ErrorHighlight.spot to establish the column of the error.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments