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

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?


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

It's not much better, but you can just reraise the exception with a new message:

raise $!, "Problem with string number #{i}: #{$!}"

You can also get a modified exception object yourself with the exception method:

new_exception = $!.exception "Problem with string number #{i}: #{$!}"
raise new_exception

Here's another way:

class Exception
  def with_extra_message extra
    exception "#{message} - #{extra}"
  end
end

begin
  1/0
rescue => e
  raise e.with_extra_message "you fool"
end

# raises an exception "ZeroDivisionError: divided by 0 - you fool" with original backtrace

(revised to use the exception method internally, thanks @Chuck)

链接地址: http://www.djcxy.com/p/25838.html

上一篇: 如何在Ruby中拯救eval?

下一篇: 如何将信息添加到Ruby中的异常消息?