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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)