如何将信息添加到Ruby中的异常消息?

如何将信息添加到异常消息中,而无需在ruby中更改其类?

我目前使用的方法是

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

理想情况下,我也想保留回溯。

有没有更好的办法?


要重新生成异常并修改消息,同时保留异常类及其回溯,只需执行以下操作:

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

这将产生:

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

这并不好,但你可以用一条新消息来重新评估异常:

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

您还可以使用exception方法自己获取修改后的异常对象:

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

这是另一种方式:

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

(修改为在内部使用exception方法,谢谢@Chuck)

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

上一篇: How do I add information to an exception message in Ruby?

下一篇: Ruby custom error classes: inheritance of the message attribute