How do I add information to an exception message in Ruby?

22,191

Solution 1

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

Solution 2

It's not much better, but you can just reraise the exception with a new message:

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

You can also get a modified exception object yourself with the exception method:

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

Solution 3

I realize I'm 6 years late to this party, but...I thought I understood Ruby error handling until this week and ran across this question. While the answers are useful, there is non-obvious (and undocumented) behavior that may be useful to future readers of this thread. All code was run under ruby v2.3.1.

@Andrew Grimm asks

How do I add information to an exception message without changing its class in ruby?

and then provides sample code:

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

I think it is critical to point out that this does NOT add information to the original error instance object, but instead raises a NEW error object with the same class.

@BoosterStage says

To reraise the exception and modify the message...

but again, the provided code

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

will raise a new instance of whatever error class is referenced by $!, but it will not be the exact same instance as $!.

The difference between @Andrew Grimm's code and @BoosterStage's example is the fact that the first argument to #raise in the first case is a Class, whereas in the second case it is an instance of some (presumably) StandardError. The difference matters because the documentation for Kernel#raise says:

With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message).

If only one argument is given and it is an error object instance, that object will be raised IF that object's #exception method inherits or implements the default behavior defined in Exception#exception(string):

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

As many would guess:

...
catch StandardError => e
  raise $!
...

raises the same error referenced by $!, the same as simply calling:

...
catch StandardError => e
  raise
...

but probably not for the reasons one might think. In this case, the call to raise is NOT just raising the object in $!...it raises the result of $!.exception(nil), which in this case happens to be $!.

To clarify this behavior, consider this toy code:

      class TestError < StandardError
        def initialize(message=nil)
          puts 'initialize'
          super
        end
        def exception(message=nil)
          puts 'exception'
          return self if message.nil? || message == self
          super
        end
      end

Running it (this is the same as @Andrew Grimm's sample which I quoted above):

2.3.1 :071 > begin ; raise TestError, 'message' ; rescue => e ; puts e ; end

results in:

initialize
message

So a TestError was initialized, rescued, and had its message printed. So far so good. A second test (analogous to @BoosterStage's sample quoted above):

2.3.1 :073 > begin ; raise TestError.new('foo'), 'bar' ; rescue => e ; puts e ; end

The somewhat surprising results:

initialize
exception
bar

So a TestError was initialized with 'foo', but then #raise has called #exception on the first argument (an instance of TestError) and passed in the message of 'bar' to create a second instance of TestError, which is what ultimately gets raised.

TIL.

Also, like @Sim, I am very concerned about preserving any original backtrace context, but instead of implementing a custom error handler like his raise_with_new_message, Ruby's Exception#cause has my back: whenever I want to catch an error, wrap it in a domain-specific error and then raise that error, I still have the original backtrace available via #cause on the domain-specific error being raised.

The point of all this is that--like @Andrew Grimm--I want to raise errors with more context; specifically I want to only raise domain-specific errors from certain points in my app that can have many network-related failure modes. Then my error reporting can be made to handle the domain errors at the top level of my app and I have all the context I need for logging/reporting by calling #cause recursively until I get to the "root cause".

I use something like this:

class BaseDomainError < StandardError
  attr_reader :extra
  def initialize(message = nil, extra = nil)
    super(message)
    @extra = extra
  end
end
class ServerDomainError < BaseDomainError; end

Then if I am using something like Faraday to make calls to a remote REST service, I can wrap all possible errors into a domain-specific error and pass in extra info (which I believe is the original question of this thread):

class ServiceX
  def initialize(foo)
    @foo = foo
  end
  def get_data(args)
    begin
      # This method is not defined and calling it will raise an error
      make_network_call_to_service_x(args)
    rescue StandardError => e
      raise ServerDomainError.new('error calling service x', binding)
    end
  end
end

Yeah, that's right: I literally just realized I can set the extra info to the current binding to grab all local vars defined at the time the ServerDomainError is instantiated/raised. This test code:

begin
  ServiceX.new(:bar).get_data(a: 1, b: 2)
rescue
  puts $!.extra.receiver
  puts $!.extra.local_variables.join(', ')
  puts $!.extra.local_variable_get(:args)
  puts $!.extra.local_variable_get(:e)
  puts eval('self.instance_variables', $!.extra)
  puts eval('self.instance_variable_get(:@foo)', $!.extra)
end

will output:

exception
#<ServiceX:0x00007f9b10c9ef48>
args, e
{:a=>1, :b=>2}
undefined method `make_network_call_to_service_x' for #<ServiceX:0x00007f9b10c9ef48 @foo=:bar>
@foo
bar

Now a Rails controller calling ServiceX doesn't particularly need to know that ServiceX is using Faraday (or gRPC, or anything else), it just makes the call and handles BaseDomainError. Again: for logging purposes, a single handler at the top level can recursively log all the #causes of any caught errors, and for any BaseDomainError instances in the error chain it can also log the extra values, potentially including the local variables pulled from the encapsulated binding(s).

I hope this tour has been as useful for others as it was for me. I learned a lot.

UPDATE: Skiptrace looks like it adds the bindings to Ruby errors.

Also, see this other post for info about how the implementation of Exception#exception will clone the object (copying instance variables).

Solution 4

Here's another way:

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

(revised to use the exception method internally, thanks @Chuck)

Solution 5

My approach would be to extend the rescued error with an anonymous module that extends the error's message method:

def make_extended_message(msg)
    Module.new do
      @@msg = msg
      def message
        super + @@msg
      end
    end
end

begin
  begin
      raise "this is a test"
  rescue
      raise($!.extend(make_extended_message(" that has been extended")))
  end
rescue
    puts $! # just says "this is a test"
    puts $!.message # says extended message
end

That way, you don't clobber any other information in the exception (i.e. its backtrace).

Share:
22,191
oligan
Author by

oligan

In part of my spare time, I work on fun programming projects. One was trying to analyze what underlies Wikipedia's Get to Philosophy game. I also worked on one called the "Small Eigen Collider". I'm currently learning Japanese, and I'm an active participant in lang-8.com, a website where you write journal entries in a language you're learning, and get corrected by native speakers of that language. In return, you correct people writing entries in your native language. Recently, I've been asking a few questions prompted by slightly incorrect English I've encountered on lang-8.

Updated on July 05, 2022

Comments

  • oligan
    oligan almost 2 years

    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?

  • oligan
    oligan about 14 years
    The first snippet is what I'm after. Looking at the documentation for Kernel#raise, it says that if you have more than one argument, the first item can be either an Exception class, or an object that returns an exception when .exception is called. I think my brain has just had an exception.
  • oligan
    oligan about 14 years
    For those curious, if an exception occurs in message, you don't get a Stack Overflow, but if you were to do so in Exception#initialize, you do.
  • Dan Rosenstark
    Dan Rosenstark about 14 years
    but wouldn't this nix the original message? Wouldn't @Mark Rushakoff's approach be more conservative?
  • Dan Rosenstark
    Dan Rosenstark about 14 years
    And thanks to Ruby being dynamic yet strongly typed, it's easy to get an Exception in the message method. Just try to add a String and number together :)
  • Ralph Sinsuat
    Ralph Sinsuat about 14 years
    @yar: Easily worked around by doing super + String(@@msg) or equivalent.
  • Dan Rosenstark
    Dan Rosenstark about 14 years
    To be just a bit polemic, your first instinct was not to do that. And you probably wouldn't think of that in your unit tests either (the holy grail of dynamic langs). So someday it would blow up at runtime, and THEN you'd add that safeguard.
  • Dan Rosenstark
    Dan Rosenstark about 14 years
    I'm not JUST complaining about dynamic langs: I'm also thinking about how to defensively program in them.
  • Chuck
    Chuck about 14 years
    @yar: No, this doesn't nix the original message. That's the entire purpose of the #{$!} interpolation. It would nix the original message if you left that out, just like if you left out the call to super in Mark's method. I would frankly say my way is more conservative, since it's just using the language's intended exception re-raising mechanisms, whereas Mark's solution involves creating a whole module and redefining the message method just to get the same effect.
  • Chuck
    Chuck about 14 years
    As another example of the hazards of dynamic-yet-strong typing, this will also fail if the exception did not already have a message, because NilClass doesn't define the + operator. It would probably be better in a lot of ways to use interpolation — def message() "#{super} #{@@msg}" end.
  • Dan Rosenstark
    Dan Rosenstark about 14 years
    Okay, thanks for the explanation, that's actually quite cool. I didn't realize that raise can take more than one param... I should've guessed that re-raising errors was already contemplated in Ruby, as it is a necessary thing.
  • oligan
    oligan almost 11 years
    Why are you rescuing from the Exception class, rather than StandardError?
  • Sim
    Sim almost 11 years
    @AndrewGrimm rescuing StandardError does not cover the kinds of edge cases that tend to occur with greater frequency when the proverbial hits the fan. Good examples are LoadError and NotImplementedError. We've also had cases of #to_s causing stack overflows as they smartly try to produce meaningful messages in complex data structures. You just don't know what will happen.
  • Jordan Running
    Jordan Running over 9 years
    On the line beginning with raise, is there a reason to use $! instead of e? They're the same object.
  • Ryenski
    Ryenski about 9 years
    @Jordan e === $! so yes you could use e instead of $1, assuming e is defined. The advantage of $! is that it is always available in an Exception block. Also of note is that $@ === e.backtrace.
  • Tyler Rick
    Tyler Rick about 9 years
    Hmm, this is strange (and unfortunate). It seems that overridding message does not have any affect on the exception's other methods such as to_s and inspect. For example: begin; 0/0; rescue; puts $!.extend(Module.new do; def message; super + ' With additional info!'; end; end).inspect; end #<ZeroDivisionError: divided by 0> (I would have expected that inspect would have been defined in terms of message, such as def inspect; "<#{self.class}: #{message}"; end. Am I incorrect?)
  • Tyler Rick
    Tyler Rick about 9 years
    Ah, I see. message is actually defined in terms of to_s (not the other way around): return rb_funcall(exc, rb_intern("to_s"), 0, 0);
  • Matt Zukowski
    Matt Zukowski about 9 years
    You can also use e2 = e.class.new "Foo: #{e}" to create a new exception of the same type, and then e2.set_backtrace(e.backtrace) to take the backtrace from the original exception.
  • Mitch VanDuyn
    Mitch VanDuyn over 8 years
    wish I could give a +++ for this answer as I learned a lot from it (and the follow up comments)
  • mlovic
    mlovic over 6 years
    Note that rescuing Exception is probably not what you want stackoverflow.com/questions/10048173/….
  • mlovic
    mlovic over 6 years
    Also note that $! is a global variable pointing to the last exception raised in running Ruby program. It could be overwritten during the rescue block by another exception being raised in another thread. That is one reason to prefer using e.
  • Jason Denney
    Jason Denney over 5 years
    Note that this will alter the backtrace, unless $!.backtrace is passed as the 3rd argument
  • Qqwy
    Qqwy almost 5 years
    @mlovic In this case, where the Exception immediately gets re-raised, it is probably what you want.
  • pedz
    pedz about 4 years
    At some point, the print out of an uncaught exception now prints out the previous exception as well. As you say, the various choices are creating and raising a new exception and thus, the output has two stacks. I've yet to find a way to raise the same exception with a modified message.
  • pedz
    pedz about 4 years
    At some point, the code that prints the exception to STDERR for an exception that isn't caught now prints out the previous exception as well. All the methods on this page raise a new exception and thus the print out now has two stacks. I've yet to see a way to raise the same exception with an appended message.