Stack traces

suggest change

A stack trace (Ruby calls it a backtrace) is the list of method calls that were active when something happened. It is usually the first thing you look at when a program crashes: it tells you where the error was raised and how execution got there.

This article covers:

The examples were run with Ruby 4.0. The trace format described here (method names in single quotes, with the class name, such as 'Integer#/') is used since Ruby 3.4. Older versions printed `/' instead.

Reading a stack trace

Here's a small program that fails on its second row:

def parse_age(str)
  Integer(str)
end

def load_user(row)
  { name: row[0], age: parse_age(row[1]) }
end

rows = [["Ann", "34"], ["Bob", "n/a"]]
rows.each { |row| p load_user(row) }
$ ruby basic.rb
{name: "Ann", age: 34}
basic.rb:2:in 'Kernel#Integer': invalid value for Integer(): "n/a" (ArgumentError)

  Integer(str)
          ^^^
	from basic.rb:2:in 'Object#parse_age'
	from basic.rb:6:in 'Object#load_user'
	from basic.rb:10:in 'block in <main>'
	from basic.rb:10:in 'Array#each'
	from basic.rb:10:in '<main>'

The trace is printed to stderr and the process exits with status 1. Read it from the top:

Each frame is file:line:in 'label'. Some labels you'll see:

Label Meaning
'Object#parse_age' instance method parse_age defined on Object (top-level defs go there)
'Report.build' singleton (class) method build of Report
'block in Report#render' a block inside Report#render
'<main>' top level of the main script
'<top (required)>' top level of a file loaded with require
'<class:Report>' code in the body of class Report

Methods written in C, like Kernel#Integer and Array#each, have no Ruby source. Ruby shows them with the file and line of the Ruby code that called them, which is why Kernel#Integer above is at basic.rb:2.

The most useful frame is often not the top one. The top frame says Integer() failed, but the bug, if there is one, is in your code a few frames down: parse_age doesn't handle bad input, or the data in rows is wrong. Scan down to the first frame in your own code.

Getting the backtrace from an exception

When you rescue an exception, its trace is still available:

def parse_age(str) = Integer(str)

def load_user(row)
  { name: row[0], age: parse_age(row[1]) }
end

begin
  load_user(["Bob", "n/a"])
rescue ArgumentError => e
  puts e.message
  puts e.backtrace.first(3)
  puts "---"
  loc = e.backtrace_locations[1]
  p loc.class
  puts "path=#{loc.path} lineno=#{loc.lineno} label=#{loc.label} base_label=#{loc.base_label}"
end
$ ruby rescue.rb
invalid value for Integer(): "n/a"
rescue.rb:1:in 'Kernel#Integer'
rescue.rb:1:in 'Object#parse_age'
rescue.rb:4:in 'Object#load_user'
---
Thread::Backtrace::Location
path=rescue.rb lineno=1 label=Object#parse_age base_label=parse_age

An exception that was created but never raised has no trace: both methods return nil.

Printing it like Ruby does

full_message returns the same text Ruby prints for an uncaught exception, including the cause and the error_highlight snippet. It's what you want for logs and error reports:

puts e.full_message(highlight: false)
rescue.rb:1:in 'Kernel#Integer': invalid value for Integer(): "n/a" (ArgumentError)

def parse_age(str) = Integer(str)
                             ^^^
	from rescue.rb:1:in 'Object#parse_age'
	from rescue.rb:4:in 'Object#load_user'
	from rescue.rb:8:in '<main>'

highlight: false turns off ANSI colors and bold. Leave it at the default when printing to a terminal and set it to false when writing to a file. order: :bottom prints the trace in the old Python-like order, with the outermost frame first:

def inner = raise(KeyError, "missing :token")
def outer = inner

begin
  outer
rescue KeyError => e
  puts e.full_message(highlight: false, order: :bottom)
end
$ ruby order.rb
Traceback (most recent call last):
	2: from order.rb:5:in '<main>'
	1: from order.rb:2:in 'Object#outer'
order.rb:1:in 'Object#inner': missing :token (KeyError)

Adding context to the message

detailed_message is the method that builds the "message (Class)" part plus the highlight snippet. Override it in your own exception class to show extra data in every trace, without changing message:

class QueryError < StandardError
  def initialize(msg, sql:)
    super(msg)
    @sql = sql
  end

  def detailed_message(highlight: false, **)
    "#{super}\n  SQL: #{@sql}"
  end
end

def find_user(id)
  raise QueryError.new("syntax error near FORM", sql: "SELECT * FORM users WHERE id = #{id}")
end

find_user(7)
$ ruby detailed.rb
detailed.rb:13:in 'Object#find_user': syntax error near FORM (QueryError)
  SQL: SELECT * FORM users WHERE id = 7
	from detailed.rb:16:in '<main>'

See Adding information to custom exceptions for more about custom exception classes.

The current stack: caller and caller_locations

You don't need an exception to get a stack trace. caller returns the stack of the current method's callers as strings, and caller_locations returns Location objects:

def where_am_i
  puts "caller:"
  puts caller.map { "  #{_1}" }
  puts "caller(0, 2):"
  puts caller(0, 2).map { "  #{_1}" }
  loc = caller_locations(1, 1).first
  puts "called from #{loc.path}:#{loc.lineno} in #{loc.label}"
end

class Report
  def self.build = new.render
  def render = [1].each { where_am_i }
end

module Helpers
  def self.run
    yield
  end
end

Helpers.run { Report.build }
$ ruby caller.rb
caller:
  caller.rb:12:in 'block in Report#render'
  caller.rb:12:in 'Array#each'
  caller.rb:12:in 'Report#render'
  caller.rb:11:in 'Report.build'
  caller.rb:21:in 'block in <main>'
  caller.rb:17:in 'Helpers.run'
  caller.rb:21:in '<main>'
caller(0, 2):
  caller.rb:5:in 'Object#where_am_i'
  caller.rb:12:in 'block in Report#render'
called from caller.rb:12 in block in Report#render

Both take (start, length) or a range:

Ask only for what you need. Building the whole stack as strings is much slower than getting one Location. Measured 100,000 times from 50 frames deep with Benchmark.bm (absolute numbers vary by machine):

                             user     system      total        real
caller                   3.313000   0.062000   3.375000 (  3.833802)
caller_locations         0.453000   0.000000   0.453000 (  0.493292)
caller_locations(1,1)    0.031000   0.000000   0.031000 (  0.024636)

This matters if you record the caller on every call, for example in a query logger that notes which line issued each SQL query.

For the location of the current line, use __FILE__, __LINE__, __method__ and __dir__; they are resolved at parse time and cost nothing.

Pointing a warning at the caller

A deprecation warning should point at the code that called the deprecated method, not at the method itself. warn does this with uplevel::

module Legacy
  def self.fetch(url)
    warn "Legacy.fetch is deprecated, use HTTP.get", uplevel: 1
    "body of #{url}"
  end
end

def sync_feed
  Legacy.fetch("https://example.com/feed")
end

sync_feed
$ ruby warn.rb
warn.rb:9: warning: Legacy.fetch is deprecated, use HTTP.get

uplevel: 0 would report line 3, inside Legacy.fetch. uplevel: 1 reports the caller, line 9.

Wrapping and re-raising

When you rescue an exception and raise a different one, Ruby stores the original in cause automatically:

class ConfigError < StandardError; end

def read_port(s) = Integer(s)

def load_config(text)
  read_port(text)
rescue ArgumentError => e
  raise ConfigError, "bad port in config: #{text.inspect}"
end

def reraise_same
  read_port("x")
rescue ArgumentError => e
  puts "logging #{e.class}"
  raise          # same exception object, same backtrace
end

begin
  load_config("eighty")
rescue ConfigError => e
  puts "#{e.class}: #{e.message}"
  puts "  at #{e.backtrace.first}"
  puts "cause: #{e.cause.class}: #{e.cause.message}"
  puts "  at #{e.cause.backtrace.first}"
end

begin
  reraise_same
rescue => e
  puts "#{e.class} at #{e.backtrace.first}"
end
$ ruby reraise.rb
ConfigError: bad port in config: "eighty"
  at reraise.rb:8:in 'Object#load_config'
cause: ArgumentError: invalid value for Integer(): "eighty"
  at reraise.rb:3:in 'Kernel#Integer'
logging ArgumentError
ArgumentError at reraise.rb:3:in 'Kernel#Integer'

If the wrapped exception is never rescued, Ruby prints both traces, the cause after the main one:

class ConfigError < StandardError; end

def read_port(s) = Integer(s)

def load_config(text)
  read_port(text)
rescue ArgumentError
  raise ConfigError, "bad port in config"
end

load_config("eighty")
$ ruby uncaught_cause.rb
uncaught_cause.rb:8:in 'Object#load_config': bad port in config (ConfigError)
	from uncaught_cause.rb:11:in '<main>'
uncaught_cause.rb:3:in 'Kernel#Integer': invalid value for Integer(): "eighty" (ArgumentError)

def read_port(s) = Integer(s)
                           ^
	from uncaught_cause.rb:3:in 'Object#read_port'
	from uncaught_cause.rb:6:in 'Object#load_config'
	from uncaught_cause.rb:11:in '<main>'

full_message includes the cause too, so logging e.full_message is enough. Logging only e.backtrace loses it.

Setting a backtrace yourself

The third argument of raise is the backtrace to use. Since Ruby 3.4 it can be an array of Location objects, so backtrace_locations keeps working on the new exception:

class FetchError < StandardError; end

def fetch = Integer("oops")

begin
  begin
    fetch
  rescue ArgumentError => e
    raise FetchError, "fetch failed", e.backtrace_locations
  end
rescue FetchError => e
  puts e.backtrace.first(2)
  p e.backtrace_locations&.first&.class
end

err = RuntimeError.new("built by hand")
p err.backtrace
err.set_backtrace(["worker.rb:10:in 'Worker#perform'"])
p err.backtrace
p err.backtrace_locations
$ ruby keepbt.rb
keepbt.rb:3:in 'Kernel#Integer'
keepbt.rb:3:in 'Object#fetch'
Thread::Backtrace::Location
nil
["worker.rb:10:in 'Worker#perform'"]
nil

Prefer letting cause do its job. Copying the old trace onto a new exception hides where the new one was raised. It's useful when an exception crosses a boundary, for example a job runner that re-creates an error reported by a worker process, where set_backtrace with strings is the only option. As the last line shows, backtrace_locations is nil when the trace was set from strings.

Stack traces of threads

An exception in a thread other than the main one doesn't stop the program. By default (Thread.report_on_exception is true), Ruby prints the trace to stderr when the thread dies, and join or value re-raises the exception in the joining thread with its original backtrace:

def compute(x) = 10 / x

t = Thread.new { compute(0) }
sleep 0.1
puts "main thread keeps running"
begin
  t.join
rescue ZeroDivisionError => e
  puts "join re-raised: #{e.message}"
  puts e.backtrace
end
$ ruby thread_err.rb
#<Thread:0x0000014cb1a4b6a0 thread_err.rb:3 run> terminated with exception (report_on_exception is true):
thread_err.rb:1:in 'Integer#/': divided by 0 (ZeroDivisionError)
	from thread_err.rb:1:in 'Object#compute'
	from thread_err.rb:3:in 'block in <main>'
main thread keeps running
join re-raised: divided by 0
thread_err.rb:1:in 'Integer#/'
thread_err.rb:1:in 'Object#compute'
thread_err.rb:3:in 'block in <main>'

Thread#backtrace returns what another thread is doing right now. Dumping all threads is the standard way to find out why a process is stuck:

def wait_for_job(queue) = queue.pop

def dump_threads(io = $stdout)
  Thread.list.each do |t|
    io.puts "Thread #{t.name || t.inspect} (#{t.status})"
    (t.backtrace || []).each { io.puts "    #{_1}" }
  end
end

Thread.current.name = "main"
queue = Thread::Queue.new
worker = Thread.new { wait_for_job(queue) }
worker.name = "worker-1"
sleep 0.1

dump_threads
queue << :stop
worker.join
$ ruby threads.rb
Thread main (run)
    threads.rb:6:in 'Thread#backtrace'
    threads.rb:6:in 'block in Object#dump_threads'
    threads.rb:4:in 'Array#each'
    threads.rb:4:in 'Object#dump_threads'
    threads.rb:16:in '<main>'
Thread worker-1 (sleep)
    threads.rb:1:in 'Thread::Queue#pop'
    threads.rb:1:in 'Object#wait_for_job'
    threads.rb:12:in 'block in <main>'

Naming threads makes these dumps much easier to read. In a long-running server, call dump_threads from a signal handler (trap("TTIN") { dump_threads($stderr) } on Unix) or an admin endpoint. Sidekiq and Puma have this built in; see Signals and graceful shutdown.

Deep recursion

Infinite recursion ends with SystemStackError. Its backtrace has thousands of identical frames:

def forever(n) = forever(n + 1)

begin
  forever(0)
rescue SystemStackError => e
  puts "#{e.class}: #{e.message}"
  puts "frames: #{e.backtrace.size}"
  puts e.backtrace.first(2)
  puts e.backtrace.last(1)
end
$ ruby deep.rb
SystemStackError: stack level too deep
frames: 10921
deep.rb:1:in 'Object#forever'
deep.rb:1:in 'Object#forever'
deep.rb:4:in '<main>'

The frame count depends on the platform and the size of each frame. When printing an uncaught SystemStackError, Ruby shows the first few frames and then ... 11901 levels.... The repeating frame tells you which method recurses. Look at the last frames to see where the recursion started. See Recursion in Ruby for how to avoid it.

For any long trace you can limit how much Ruby prints with --backtrace-limit:

$ ruby --backtrace-limit=2 limit.rb
limit.rb:4:in 'Object#d': deep down (RuntimeError)
	from limit.rb:3:in 'Object#c'
	from limit.rb:2:in 'Object#b'
	 ... 2 levels...

Filtering out library frames

In a real application, most frames come from gems and the standard library: a Rails request can easily have 100 frames, and only a handful are yours. A backtrace cleaner keeps the frames under your project directory:

require "json"

class BacktraceCleaner
  def initialize(root: Dir.pwd)
    @root = File.expand_path(root) + "/"
    @noise = (Gem.path + [RbConfig::CONFIG["rubylibdir"]]).map { File.expand_path(_1) }
  end

  def clean(locations)
    locations
      .reject { |l| l.absolute_path.nil? || @noise.any? { l.absolute_path.start_with?(_1) } }
      .map { |l| "#{l.absolute_path.delete_prefix(@root)}:#{l.lineno}:in '#{l.label}'" }
  end
end

def load_settings(text) = JSON.parse(text)

begin
  load_settings('{"port": 80,}')
rescue JSON::ParserError => e
  puts "full backtrace:"
  puts e.backtrace.map { "  #{_1}" }
  puts "cleaned:"
  puts BacktraceCleaner.new.clean(e.backtrace_locations).map { "  #{_1}" }
end
$ ruby clean.rb
full backtrace:
  C:/Ruby40-x64/lib/ruby/4.0.0/json/common.rb:353:in 'JSON::Ext::Parser.parse'
  C:/Ruby40-x64/lib/ruby/4.0.0/json/common.rb:353:in 'JSON.parse'
  clean.rb:16:in 'Object#load_settings'
  clean.rb:19:in '<main>'
cleaned:
  clean.rb:16:in 'Object#load_settings'
  clean.rb:19:in '<main>'

Gem.path lists the directories where gems are installed and rubylibdir is the standard library. The paths in the full trace depend on where Ruby is installed. absolute_path is nil for code from eval and is dropped here.

Filter for display only. Keep the full trace in error reports: sometimes the bug is in how you call a library, and you need its frames to see that.

Tools already do this:

Logging and crash reports

When you rescue an exception and continue, log its trace. Logger formats exceptions passed to it as the message, class and backtrace:

require "logger"

logger = Logger.new($stdout)

def charge(amount)
  raise ArgumentError, "amount must be positive, got #{amount}" unless amount.positive?
end

begin
  charge(-5)
rescue => e
  logger.error(e)
end
$ ruby log.rb
E, [2026-10-17T22:11:23.905903 #15704] ERROR -- : amount must be positive, got -5 (ArgumentError)
log.rb:6:in 'Object#charge'
log.rb:10:in '<main>'

This leaves out the cause. If you wrap exceptions, log e.full_message(highlight: false) instead. See Logging for configuring loggers.

For a script or worker that runs unattended, save the trace of the exception that kills the process. In an at_exit handler, $! is the exception that is ending the program (or nil on a normal exit):

at_exit do
  err = $!
  if err && !err.is_a?(SystemExit)
    File.write("crash.log", "#{Time.now.utc} pid=#{Process.pid}\n#{err.full_message(highlight: false)}")
    warn "crash report written to crash.log"
  end
end

def process(items) = items.map { _1.upcase }

process(["a", nil])
$ ruby crash.rb
crash report written to crash.log
crash.rb:9:in 'block in Object#process': undefined method 'upcase' for nil (NoMethodError)

def process(items) = items.map { _1.upcase }
                                   ^^^^^^^
	from crash.rb:9:in 'Array#map'
	from crash.rb:9:in 'Object#process'
	from crash.rb:11:in '<main>'

$ cat crash.log
2026-10-17 20:10:29 UTC pid=27696
crash.rb:9:in 'block in Object#process': undefined method 'upcase' for nil (NoMethodError)

def process(items) = items.map { _1.upcase }
                                   ^^^^^^^
	from crash.rb:9:in 'Array#map'
	from crash.rb:9:in 'Object#process'
	from crash.rb:11:in '<main>'

SystemExit is skipped because exit raises it, and a normal exit 1 is not a crash. Ruby still prints the trace to stderr and exits with status 1 after the handler runs. Error tracking services such as Sentry, Honeybadger and Bugsnag do the same thing: they capture backtrace_locations and cause, and group errors by their top frames.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents