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.