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.

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
    An advertisement for Honeybadger that reads 'Turn your logs into events.'

    "Splunk-like querying without having to sell my kidneys? nice"

    That’s a direct quote from someone who just saw Honeybadger Insights. It’s a bit like Papertrail or DataDog—but with just the good parts and a reasonable price tag.

    Best of all, Insights logging is available on our free tier as part of a comprehensive monitoring suite including error tracking, uptime monitoring, status pages, and more.

    Start logging for FREE
    Simple 5-minute setup — No credit card required