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?
In my experience, when it comes to writing exception messages, most developers approach the job with one of these mindsets: Write the shortest possible exception message; if possible, ignore good grammar, punctuation, and proper spelling. Write lovingly crafted error messages for the end users.
Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).
Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With