What happens when you rescue an exception and re-raise another one? It used to be that the original exception was lost forever. But since Ruby 2.1, you can access these nested exceptions via the cause method.

I've already published a more detailed look at causes, but for now a simple example will work. In the code below we raise three nested exceptions, then use the Exception#cause method to access them.

def caused_exception
  begin
    begin
      raise RuntimeError.new("This is the root cause raised at #{ Time.now }")
    rescue
      raise RuntimeError.new("This is the second cause raised at #{ Time.now }")
    end
  rescue
    raise RuntimeError.new("This is the third cause raised at #{ Time.now }")
  end
end


begin
  caused_exception
rescue => e
  puts e              # This is the third cause raised at 2015-08-04 10:07:11 -0700
  puts e.cause        # This is the second cause raised at 2015-08-04 10:07:11 -0700
  puts e.cause.cause  # This is the root cause raised at 2015-08-04 10:07:11 -0700
end

Viewing causes in Honeybadger

As of today, any error reported to Honeybadger will have its cause information attached. You'll find it right underneath the main backtrace in a section titled "Nested Exceptions". The only thing you need to do is to make sure that you're running the latest version of our gem.

Here's what the exception shown above would look like:

causes

Each cause has its own separate backtrace which you can expand by clicking. You have direct links to your git repo and to open the file in a local editor, just like the "normal" backtrace.

causes_expanded

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
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