如何在Ruby中的异常消息中添加信息? [英] How do I add information to an exception message in Ruby?
本文介绍了如何在Ruby中的异常消息中添加信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用的方法是
strings.each_with_index do | string,i |
begin
do_risky_operation(string)
rescue
raise $ !. class,string number#{i}的问题:#{$!}
end
end
理想情况下,我也想保留回溯。
有更好的方法吗?
解决方案
要重新启动异常并修改消息,保留异常类及其回溯,只需执行以下操作:
strings.each_with_index do | string,i |
begin
do_risky_operation(string)
rescue Exception => e
raise $ !,字符串号#{i}的问题:#{$!},$ !.backtrace
end
end
哪个会产生:
#RuntimeError:字符串号0的问题:原始错误信息在这里
#backtrace ...
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...
这篇关于如何在Ruby中的异常消息中添加信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文