ruby - re-raise exception with sub-exception

Ruby 2.1 added Exception#cause feature to solve this problem.


Take a look at the tricks from the talk Exceptional Ruby by Avdi Grimm:

class MyError < StandardError
  attr_reader :original
  def initialize(msg, original=nil);
    super(msg);
    @original = original;
  end
end
# ...
rescue => error
  raise MyError.new("Error B", error)
end

For Ruby prior 2.1, you may extend StandardError:

class StandardError
   attr_accessor :original
end

and when you raise an exception, just set this property:

def reraise ex, original
   ex.original = original
   raise ex
end

rescue StandardError => e
   reraise ArgumentError.new('Message'), e
end

With this approach you will be able to raise standard ruby errors and set parent error for them, not only your custom errors.

For ruby 2.1 and above you can use Exception#cause as mentioned in another answer.