Nippysaurus
Nippysaurus

Reputation: 20378

ruby - re-raise exception with sub-exception

I come from a C# background where I usually re-raise exceptions with the original exception contained inside the parent exception. Is a similar concept available in Ruby? How do I detect and raise an exception while maintaining the context of the lower level exception?

Upvotes: 17

Views: 7843

Answers (3)

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

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.

Upvotes: 7

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

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

Upvotes: 14

Henrik
Henrik

Reputation: 3704

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

Upvotes: 16

Related Questions