Helpful error messages: error_highlight, syntax_suggest, did_you_mean
suggest changeWhen a Ruby program crashes, the error message is more than a line of text. Three libraries that ship with Ruby add extra information to it:
- error_highlight (Ruby 3.1) prints the failing line and puts
^^^^under the exact expression that raised. - syntax_suggest (Ruby 3.2) finds where a missing or extra
end,)or}actually is when a file doesn't parse. - did_you_mean (Ruby 2.3) suggests the name you probably meant when you mistype a method, variable, constant, hash key or required file.
All three are default gems, loaded automatically when Ruby starts. You don't need to require anything to get them.
This article covers reading their output, using them from your own code (ErrorHighlight.spot, DidYouMean::SpellChecker, custom spell checkers for your own exceptions), and turning them off. The examples were run with Ruby 4.0.7, error_highlight 0.7.2, syntax_suggest 2.0.3 and did_you_mean 2.0.0. Check yours with gem list error_highlight syntax_suggest did_you_mean.
How Ruby prints the backtrace itself, full_message and overriding detailed_message in your own exception classes are covered in Stack traces.
error_highlight: which expression failed
Before Ruby 3.1, this error told you the line, but not which of the four [] calls on it got nil:
config = { db: { host: "localhost" } }
port = config[:db][:port].to_i + config[:cache][:port].to_i
$ ruby chain.rb
chain.rb:2:in '<main>': undefined method '[]' for nil (NoMethodError)
port = config[:db][:port].to_i + config[:cache][:port].to_i
^^^^^^^
The ^^^^^^^ is under [:port] after config[:cache]. So config[:cache] is nil, and config[:db][:port] was fine (nil.to_i is 0).
For NoMethodError and NameError, the marker points at the method or variable name. For TypeError and ArgumentError (since Ruby 3.2) it points at the argument:
count = 5
puts "Items: " + count
$ ruby typeerr.rb
typeerr.rb:2:in 'String#+': no implicit conversion of Integer into String (TypeError)
puts "Items: " + count
^^^^^
from typeerr.rb:2:in '<main>'
The highlight is always for the top frame of the backtrace. When the error happens inside a method you called, the snippet shows that method's line, and you read the from lines to see who called it:
def area(w, h) = w * h
total = 1 + area(3, "4").size + "x"
$ ruby args.rb
args.rb:1:in 'Integer#*': String can't be coerced into Integer (TypeError)
def area(w, h) = w * h
^
from args.rb:1:in 'Object#area'
from args.rb:2:in '<main>'
Wrong number of arguments: caller and callee
Ruby 4.0 improved ArgumentError for wrong arity and keyword mistakes. It shows both the call and the method definition, which are often in different files:
def send_email(to, subject, body:)
"#{to}: #{subject}"
end
send_email("ann@example.com", body: "Hi")
$ ruby arity.rb
arity.rb:1:in 'Object#send_email': wrong number of arguments (given 1, expected 2; required keyword: body) (ArgumentError)
caller: arity.rb:5
| send_email("ann@example.com", body: "Hi")
^^^^^^^^^^
callee: arity.rb:1
| def send_email(to, subject, body:)
^^^^^^^^^^
from arity.rb:5:in '<main>'
The same format is used for unknown and missing keywords:
def paint(color:, finish: :matte) = "#{color} #{finish}"
paint(color: "red", finsh: :gloss)
$ ruby unk.rb
unk.rb:1:in 'Object#paint': unknown keyword: :finsh (ArgumentError)
caller: unk.rb:2
| paint(color: "red", finsh: :gloss)
^^^^^
callee: unk.rb:1
| def paint(color:, finish: :matte) = "#{color} #{finish}"
^^^^^
from unk.rb:2:in '<main>'
Note that did_you_mean doesn't suggest finish here. It doesn't check keyword arguments.
When there is no highlight
error_highlight reads the source file to find the expression, so it can't help when there is no file:
- code run with
ruby -e - code passed to
evalas a string - a source file that changed or was deleted after it was loaded (the highlight may point at the wrong place)
It also only highlights an expression that fits on one line. If the failing call spans several lines, you get the message without a snippet.
The highlight is not part of message
The snippet is added by Exception#detailed_message, not by message. That matters when you rescue an exception and show it to a user or match on its text:
begin
[1, 2, 3].frist
rescue NoMethodError => e
p e.message
p e.detailed_message(highlight: false)
puts e.full_message(highlight: false)
end
$ ruby msg.rb
"undefined method 'frist' for an instance of Array"
"undefined method 'frist' for an instance of Array (NoMethodError)\n\n [1, 2, 3].frist\n ^^^^^^\nDid you mean? first"
msg.rb:2:in '<main>': undefined method 'frist' for an instance of Array (NoMethodError)
[1, 2, 3].frist
^^^^^^
Did you mean? first
messageis the plain message. Use it in user-facing text and in tests.detailed_messageadds the class name, the error_highlight snippet and the did_you_mean suggestion. Passerror_highlight: falseto leave out just the snippet.full_messageisdetailed_messageplus the backtrace. Log this one.
ErrorHighlight.spot: the location as data
ErrorHighlight.spot returns the position that the ^^^^ marker is drawn from, as a hash:
def price_for(order) = order[:items].sum { _1[:price] } * order[:qty]
begin
price_for({ items: [{ price: 5 }], qty: nil })
rescue TypeError => e
spot = ErrorHighlight.spot(e)
p spot.except(:script_lines)
puts e.message
puts "---"
puts e.detailed_message
puts "---"
puts e.detailed_message(error_highlight: false)
end
$ ruby spot.rb
{first_lineno: 1, first_column: 58, last_lineno: 1, last_column: 69, snippet: "def price_for(order) = order[:items].sum { _1[:price] } * order[:qty]\n"}
nil can't be coerced into Integer
---
nil can't be coerced into Integer (TypeError)
def price_for(order) = order[:items].sum { _1[:price] } * order[:qty]
^^^^^^^^^^^
---
nil can't be coerced into Integer (TypeError)
Columns are 0-based and last_column is exclusive. spot returns nil when it can't find the source, for example for an exception that was never raised or that came from eval.
A practical use is printing errors in the file:line:column: message format that editors and CI annotations understand:
def format_location(e)
loc = e.backtrace_locations.first
spot = ErrorHighlight.spot(e)
col = spot ? spot[:first_column] + 1 : 1
"#{loc.path}:#{loc.lineno}:#{col}: #{e.class}: #{e.message}"
end
def total(order) = order[:qty] * order[:price]
[
-> { { name: "x" }.fetch(:name).upcse },
-> { total({ qty: 2, price: nil }) },
-> { eval("nil.size + 1") },
].each do |job|
job.call
rescue => e
puts format_location(e)
end
begin
total({ qty: 2, price: "9" })
rescue TypeError => e
caller_loc = e.backtrace_locations[2]
spot = ErrorHighlight.spot(e, backtrace_location: caller_loc)
puts spot[:snippet]
puts " " * spot[:first_column] + "^" * (spot[:last_column] - spot[:first_column])
end
$ ruby editor.rb
editor.rb:11:34: NoMethodError: undefined method 'upcse' for an instance of String
editor.rb:8:34: TypeError: nil can't be coerced into Integer
(eval at editor.rb:13):1:1: NoMethodError: undefined method 'size' for nil
total({ qty: 2, price: "9" })
^^^^^
The eval line falls back to column 1 because spot returned nil. The backtrace_location: option highlights a different frame. Here frame 2 is the call to total in the main script (frame 0 is Integer#*, frame 1 is total).
Customizing the format
ErrorHighlight.formatter is the object that turns a spot into text. Any object with a message_for(spot) method can replace it:
class ArrowFormatter
def self.message_for(spot)
return "" unless spot[:first_lineno] == spot[:last_lineno]
line = spot[:first_lineno]
code = spot[:snippet].chomp
col = spot[:first_column]
len = spot[:last_column] - col
"\n #{line} | #{code}\n #{' ' * line.to_s.size} | #{' ' * col}#{'~' * len} here (column #{col + 1})"
end
end
ErrorHighlight.formatter = ArrowFormatter
user = { profile: nil }
puts user[:profile][:name]
$ ruby fmt.rb
fmt.rb:16:in '<main>': undefined method '[]' for nil (NoMethodError)
16 | puts user[:profile][:name]
| ~~~~~~~ here (column 20)
The formatter is per Ractor, so set it early, for example in a file required at boot.
For long lines, the default formatter trims the snippet to the terminal width and adds ... on the cut sides. Set the width yourself with max_snippet_width= (minimum 20, nil turns trimming off):
ErrorHighlight::DefaultFormatter.max_snippet_width = 40
data = { users: [{ name: "Ann", roles: ["admin"] }], groups: nil, settings: { theme: "dark" } }
puts data[:users].first[:roles].first.upcase + data[:groups].first.to_s + data[:settings][:theme]
$ ruby width.rb
width.rb:4:in '<main>': undefined method 'first' for nil (NoMethodError)
...e + data[:groups].first.to_s + dat...
^^^^^^
When stderr is not a terminal, such as in a log file or CI, the default is no trimming.
syntax_suggest: finding the missing end
A missing end is one of the most annoying Ruby errors. The parser only notices at the end of the file, so the error points at the last line, far from the actual mistake. syntax_suggest runs when a file fails to parse. It uses indentation to search for the block that doesn't balance and prints it above the parser's error:
class Inventory
def initialize
@items = {}
end
def add(name, qty)
if @items.key?(name)
@items[name] += qty
else
@items[name] = qty
end
def total
@items.values.sum
end
end
$ ruby missing_end.rb
missing_end.rb: --> missing_end.rb
Unmatched keyword, missing `end' ?
1 class Inventory
> 6 def add(name, qty)
> 7 if @items.key?(name)
> 11 end
16 end
missing_end.rb:16: syntax errors found (SyntaxError)
> 1 | class Inventory
| ^~~~~ expected an `end` to close the `class` statement
2 | def initialize
3 | @items = {}
~~~~~~
14 | @items.values.sum
15 | end
> 16 | end
| ^ unexpected end-of-input, assuming it is closing the parent top level context
There are two reports here:
- The top part, from syntax_suggest, shows the suspicious lines marked with
>, with the enclosingclassandendfor context. Theifon line 7 is closed by theendon line 11, which was meant to closedef add. Theendfor theifis missing. - The bottom part is the error from Prism, Ruby's parser since 3.4 (see Parsing Ruby code with Prism). It's correct but not helpful: it says the
classon line 1 isn't closed.
The more code there is between the mistake and the end of the file, the more useful syntax_suggest's part is.
An end too many is reported too. Here the end on line 11 is left over after an edit:
class Report
def lines(rows)
rows.map do |r|
"#{r[:name]}: #{r[:total]}"
end
end
def summary(rows)
total = rows.sum { |r| r[:total] }
"Total: #{total}"
end
end
def footer
"-- end of report --"
end
end
$ ruby extra2.rb
extra2.rb: --> extra2.rb
Unmatched `end', missing keyword (`do', `def`, `if`, etc.) ?
1 class Report
8 def summary(rows)
> 9 total = rows.sum { |r| r[:total] }
> 11 end
12 end
17 end
extra2.rb:17: syntax error found (SyntaxError)
15 | "-- end of report --"
16 | end
> 17 | end
| ^~~ unexpected 'end', ignoring it
The parser complains about line 17. syntax_suggest points at summary.
It also catches unmatched brackets and a missing do:
def report(rows)
rows.each do |r|
puts format("%-10s %5d", r[:name], r[:count]
end
end
$ ruby paren.rb
paren.rb: --> paren.rb
Unmatched `(', missing `)' ?
1 def report(rows)
2 rows.each do |r|
> 3 puts format("%-10s %5d", r[:name], r[:count]
4 end
5 end
paren.rb:4: syntax error found (SyntaxError)
2 | rows.each do |r|
3 | puts format("%-10s %5d", r[:name], r[:count]
> 4 | end
| ^~~ unexpected 'end'; expected a `)` to close the arguments
5 | end
def print_all(items)
items.each |item|
puts item
end
end
$ ruby nodo.rb
nodo.rb: --> nodo.rb
Unmatched `end', missing keyword (`do', `def`, `if`, etc.) ?
1 def print_all(items)
> 2 items.each |item|
> 4 end
5 end
nodo.rb:3: syntax errors found (SyntaxError)
1 | def print_all(items)
2 | items.each |item|
> 3 | puts item
| ^~~~ unexpected local variable or method, expecting end-of-input
4 | end
> 5 | end
| ^~~ unexpected 'end', ignoring it
syntax_suggest relies on indentation. If your file is badly indented, its guess can be off, so run a formatter (RuboCop, Standard, or your editor's) regularly. It also has a time limit, 1 second by default. For huge files, raise it with the SYNTAX_SUGGEST_TIMEOUT environment variable.
Syntax errors in required files
syntax_suggest works for any file Ruby parses: the main script, require, require_relative and load. It hooks into SyntaxError#detailed_message, so you get the same report when you rescue the error, for example in a plugin loader:
def load_plugin(path)
require_relative path
puts "loaded #{path}"
rescue SyntaxError => e
full = e.detailed_message(highlight: false)
warn "plugin #{path} has a syntax error, skipping"
warn full.gsub("#{__dir__}/", "")
:failed
end
p load_plugin("plugins/printer")
$ ruby plugin_loader.rb
plugin plugins/printer has a syntax error, skipping
--> plugins/printer.rb
Unmatched `end', missing keyword (`do', `def`, `if`, etc.) ?
1 def print_all(items)
> 2 items.each |item|
> 4 end
5 end
plugins/printer.rb:3: syntax errors found (SyntaxError)
1 | def print_all(items)
2 | items.each |item|
> 3 | puts item
| ^~~~ unexpected local variable or method, expecting end-of-input
4 | end
> 5 | end
| ^~~ unexpected 'end', ignoring it
:failed
The gsub only shortens the absolute paths in the output. e.path is the file that failed to parse. Pass syntax_suggest: false to detailed_message to get only the parser's part.
syntax_suggest needs to read the file, so code passed to eval as a string doesn't get a suggestion (e.path is then something like "(eval at loader.rb:9)").
did_you_mean: spelling suggestions
did_you_mean is the oldest of the three. When a name lookup fails, it compares the name to the names that exist and adds suggestions that are close enough:
first_name = "Ann"
puts frist_name.upcase
$ ruby name.rb
name.rb:2:in '<main>': undefined local variable or method 'frist_name' for main (NameError)
puts frist_name.upcase
^^^^^^^^^^
Did you mean? first_name
It covers more than method names. Each error below has a corrections method that returns the suggestions as an array:
def try
yield
rescue Exception => e
puts "#{e.class}: #{e.detailed_message(highlight: false, error_highlight: false)}"
puts " corrections: #{e.corrections.inspect}" if e.respond_to?(:corrections)
puts
end
class Account
attr_reader :balance
def initialize = @balance = 10
def deposit(amount) = @balance += amount
end
acct = Account.new
try { acct.deposti(5) }
try { acct.balanse }
try { Acount.new }
try { {name: "Ann", email: "a@x.io"}.fetch(:emial) }
try { ENV.fetch("PAHT") }
try { require "jsno" }
try { user = {name: "Ann"}; user => {nmae:} }
try { acct.instance_variable_get(:@balanse).foo }
$ ruby dym.rb
NoMethodError: undefined method 'deposti' for an instance of Account (NoMethodError)
Did you mean? deposit
corrections: [:deposit]
NoMethodError: undefined method 'balanse' for an instance of Account (NoMethodError)
Did you mean? balance
corrections: [:balance]
NameError: uninitialized constant Acount (NameError)
Did you mean? Account
corrections: ["Account"]
KeyError: key not found: :emial (KeyError)
Did you mean? :email
corrections: [":email"]
KeyError: key not found: "PAHT" (KeyError)
Did you mean? "PATH"
corrections: ["\"PATH\""]
LoadError: cannot load such file -- jsno (LoadError)
Did you mean? json
corrections: ["json"]
NoMatchingPatternKeyError: {name: "Ann"}: key not found: :nmae (NoMatchingPatternKeyError)
Did you mean? :name
corrections: [":name"]
NoMethodError: undefined method 'foo' for nil (NoMethodError)
corrections: []
The checkers that are registered by default:
p DidYouMean.spell_checkers.keys
["NameError", "KeyError", "NoMethodError", "LoadError", "NoMatchingPatternKeyError"]
Some things it doesn't catch:
- A misspelled instance variable is not an error.
@balanseis justnil, and the failure happens later, as the last example shows.ruby -wdoesn't warn about it either. A type checker orattr_readermethods help here, since a misspelled method name is caught. - Keyword arguments (
unknown keyword: :finsh) get no suggestion, although error_highlight shows both the call and the definition. - Very short or very different names: it only suggests names within a small edit distance, so
foofornilgets nothing.
Like the error_highlight snippet, the suggestion is added by detailed_message. e.message doesn't contain it, so tests that compare e.message don't break when a new method with a similar name is added.
Using the spell checker directly
DidYouMean::SpellChecker works on any list of words. That's handy for command-line tools, config validation and anywhere a user types a name:
colors = %w[red green blue yellow magenta cyan]
checker = DidYouMean::SpellChecker.new(dictionary: colors)
p checker.correct("gren")
p checker.correct("yelow")
p checker.correct("purple")
p checker.correct("re")
p DidYouMean::Levenshtein.distance("deposit", "deposti")
p DidYouMean::JaroWinkler.distance("deposit", "deposti").round(3)
puts DidYouMean.formatter.message_for(["status", "stats"])
$ ruby checker.rb
["green"]
["yellow"]
[]
["red"]
2
0.971
Did you mean? status
stats
correct returns an empty array when nothing is close enough, so purple gets no bad guess. It uses Jaro-Winkler similarity to find candidates and Levenshtein distance to filter them; both are available if you need the raw numbers. DidYouMean.formatter.message_for produces the same Did you mean? text Ruby prints (with a leading newline).
A spell checker for your own exceptions
To get suggestions in your own errors, write a spell checker class and register it with DidYouMean.correct_error. The class is created with the exception and must have a corrections method:
class UnknownCommandError < StandardError
attr_reader :command, :known
def initialize(command, known)
@command = command
@known = known
super("unknown command '#{command}'")
end
end
class CommandChecker
def initialize(error)
@error = error
end
def corrections
@corrections ||= DidYouMean::SpellChecker
.new(dictionary: @error.known)
.correct(@error.command)
end
end
DidYouMean.correct_error(UnknownCommandError, CommandChecker)
COMMANDS = %w[build deploy destroy status logs]
def run(cmd)
raise UnknownCommandError.new(cmd, COMMANDS) unless COMMANDS.include?(cmd)
"running #{cmd}"
end
begin
run("deplyo")
rescue UnknownCommandError => e
puts e.message
p e.corrections
end
run("stauts")
$ ruby custom.rb
unknown command 'deplyo'
["deploy"]
custom.rb:28:in 'Object#run': unknown command 'stauts' (UnknownCommandError)
Did you mean? status
from custom.rb:39:in '<main>'
correct_error prepends DidYouMean::Correctable to the exception class. That adds corrections and the Did you mean? part of detailed_message. message stays unchanged, so a CLI can print its own hint from e.corrections and the uncaught case still gets the standard output.
If did_you_mean might be disabled (see below), the DidYouMean constant won't exist. Guard the registration with if defined?(DidYouMean) in a library.
Turning them off
All three are Ruby "features" that you can disable on the command line, like gems or rubyopt. ruby --help lists them:
$ ruby --help | grep -E "error_highlight|did_you_mean|syntax_suggest"
error_highlight error_highlight (default: enabled).
did_you_mean did_you_mean (default: enabled).
syntax_suggest syntax_suggest (default: enabled).
$ ruby --disable-did_you_mean name.rb
name.rb:2:in '<main>': undefined local variable or method 'frist_name' for main (NameError)
puts frist_name.upcase
^^^^^^^^^^
$ ruby --disable=error_highlight,did_you_mean name.rb
name.rb:2:in '<main>': undefined local variable or method 'frist_name' for main (NameError)
--disable-error_highlight,--disable-syntax_suggest,--disable-did_you_meanturn off one feature.--disable=a,btakes a list.- To set it for every Ruby process, including ones started by Bundler or Rake, use
RUBYOPT, for exampleRUBYOPT=--disable-error_highlight. - To skip them for a single exception, pass
error_highlight: falseorsyntax_suggest: falsetodetailed_message, or usemessage.
Reasons to turn them off are rare. The work happens only when an error message is built, not when the exception is raised, so they cost nothing in normal code. Code that raises and rescues many NameErrors and calls detailed_message or full_message on each one does pay for the source lookup and spell check. Tools that parse Ruby's error output may also prefer the old one-line format.
Tips
- Read the
^^^^first. It tells you which receiver wasnilor which argument had the wrong type, which used to need a debugger or apcall. - When you get a
SyntaxErrorat the last line of a file, look at syntax_suggest's>lines, not at the line number in the parser's message. - Keep code formatted. syntax_suggest uses indentation to find the bad block.
- Show
e.messageto users and loge.full_message. The highlight and suggestions are in the latter only. - Use
DidYouMean::SpellCheckerfor user input such as CLI subcommands and config keys. It's already loaded, with no extra gem needed. - error_highlight shows you where something failed. To see why, stop there in a debugger: see Debugging with the debug gem, or try the code in Modern IRB, which shows the same highlighted errors.