Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
Andrew Grimm Avatar asked May 13 '10 00:05

Andrew Grimm


People also ask

How do I write an exception message?

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.

How do I raise error messages in Ruby?

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

How do you handle exceptions in Ruby?

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.


1 Answers

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... 
like image 164
Ryenski Avatar answered Sep 19 '22 14:09

Ryenski