如何在不更改ruby中的类的情况下向异常消息添加信息?
我目前使用的方法是
strings.each_with_index do |string, i|
begin
do_risky_operation(string)
rescue
raise $!.class, "Problem with string number #{i}: #{$!}"
end
end
理想情况下,我还希望保留回溯.
有更好的办法吗?
如何在不更改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...