How do I add information to an exception message in Ruby?

exception, ruby

Solution

To reraise the exception and modify the message, while preserving the exception class and its backtrace, simply do:

strings.each_with_index do |string, i|
  begin
    do_risky_operation(string)
  rescue Exception => e
    raise $!, "Problem with string number #{i}: #{$!}", $!.backtrace
  end
end

Which will yield:

# RuntimeError: Problem with string number 0: Original error message here
#     backtrace...

Problem

How do I add information to an exception message without changing its class in ruby? The approach I'm currently using is ``` strings.each_with_index do |string, i| begin do_risky_operation(string) rescue raise $!.class, "Problem with string number #{i}: #{$!}" end end ``` Ideally, I would also like to preserve the backtrace. Is there a better way?

Original source

Related problems