Nested errors in Ruby with Exception#cause

It's a common pattern in Ruby to rescue and exception and re-raise another kind of exception. But the original exception isn't lost! You can use Exception#cause to grab it. In this post we show you how.

It's a common pattern in Ruby to rescue and exception and re-raise another kind of exception. ActionView is one really obvious example of this. As I mentioned in an earlier blog post about TracePoint, ActionView swallows whatever exceptions happen in your templates and re-raises them as an ActionView::TemplateError.

Sometimes this isn't good enough. You REALLY need that original exception because it has some data in it that will help you solve a problem. Fortunately, as of Ruby 2.1, you can use the Exception#cause method to do just that.

Let's see how it works in practice. Here, we raise a NoMethodError, then immediately swallow it and raise a RuntimeError. We then catch the RuntimeError and use #cause to get the original NoMethodError.

def fail_and_reraise
  raise NoMethodError
rescue
  raise RuntimeError
end

begin
  fail_and_reraise
rescue => e
  puts "#{ e } caused by #{ e.cause }"
end

Nested backtraces and custom attributes

The #cause method actually returns the original exception object. That means that you can access any metadata that was part of the original exception. You can get the original backtrace, too.

class EatingError < StandardError
  attr_reader :food
  def initialize(food)
    @food = food
  end
end

def fail_and_reraise
  raise EatingError.new("soup")
rescue
  raise RuntimeError
end

begin
  fail_and_reraise
rescue => e
  puts "#{ e } caused by #{ e.cause } while eating #{ e.cause.food }"
  puts e.cause.backtrace.first
end


To infinity and beyond!

Though the examples above are only one level deep, nested exceptions in Ruby can have any number of levels. I'd be surprised if you ever needed to go more than three of four levels deep.

...but just for fun I thought I'd try making a 100-level deep nested exception. It's a silly little piece of code, and I hope you never see its like in production.

def recursively_raise(c=0)
  raise "Level #{ c }"
rescue => e
  if c < 100
    recursively_raise(c + 1)
  else
    recursively_print(e)
  end
end

def recursively_print(e)
  if e
    puts e
    recursively_print(e.cause)
  end
end

recursively_raise()

# ... Prints the following:
# Level 100
# Level 99
# Level 98
# etc.
What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like: