Raise custom Exception with arguments

Viewed 69950

I'm defining a custom Exception on a model in rails as kind of a wrapper Exception: (begin[code]rescue[raise custom exception]end)

When I raise the Exception, I'd like to pass it some info about a) the instance of the model whose internal functions raise the error, and b) the error that was caught.

This is going on an automated import method of a model that gets populated by POST request to from foreign datasource.

tldr; How can one pass arguments to an Exception, given that you define the Exception yourself? I have an initialize method on that Exception but the raise syntax seems to only accept an Exception class and message, no optional parameters that get passed into the instantiation process.

7 Answers

TL;DR 7 years after this question, I believe the correct answer is:

class CustomException < StandardError
  attr_reader :extra
  def initialize(message=nil, extra: nil)
    super(message)
    @extra = extra
  end
end
# => nil 
raise CustomException.new('some message', extra: "blupp")

WARNING: you will get identical results with:

raise CustomException.new(extra: 'blupp'), 'some message'

but that is because Exception#exception(string) does a #rb_obj_clone on self, and then calls exc_initialize (which does NOT call CustomException#initialize. From error.c:

static VALUE
exc_exception(int argc, VALUE *argv, VALUE self)
{
    VALUE exc;

    if (argc == 0) return self;
    if (argc == 1 && self == argv[0]) return self;
    exc = rb_obj_clone(self);
    exc_initialize(argc, argv, exc);

    return exc;
}

In the latter example of #raise up above, a CustomException will be raised with message set to "a message" and extra set to "blupp" (because it is a clone) but TWO CustomException objects are actually created: the first by CustomException.new, and the second by #raise calling #exception on the first instance of CustomException which creates a second cloned CustomException.

My extended dance remix version of why is at: https://stackoverflow.com/a/56371923/5299483

Simple pattern for custom errors with additional information

If the extra information you're looking to pass is simply a type with a message, this works well:

# define custom error class
class MyCustomError < StandardError; end

# raise error with extra information
raise MyCustomError, 'Extra Information'

The result (in IRB):

Traceback (most recent call last):
        2: from (irb):22
        1: from (irb):22:in `rescue in irb_binding'
MyCustomError (Extra Information)

Example in a class

The pattern below has become exceptionally useful for me (pun intended). It's clean, can be easily modularized, and the errors are expressive. Within my class I define new errors that inherit from StandardError, and I raise them with messages (for example, the object associated with the error).

Here's a simple example, similar to OP's original question, that raises a custom error within a class and captures the method name in the error message:

class MyUser
  # class errors
  class MyUserInitializationError < StandardError; end

  # instance methods
  def simulate_failure
    raise MyUserInitializationError, "method failed: #{__method__}"
  end
end

# example usage: 
MyUser.new.simulate_failure

# => MyUser::MyUserInitializationError (method failed: simulate_failure)

It's counterintuitive for programmers coming from e.g. Java, but the most effective way to do this is not to write a custom initializer, but rather to write your own replacement for the Exception::exception class method.

Per the Kernel#raise docs:

the first parameter should be an Exception class (or another object that returns an Exception object when sent an exception message). [Emphasis added.]

class MyException < StandardError

  class << self
    def exception(arg)
      # per `Exception::exception` docs
      return self if arg.nil? || self.equal?(arg)
      return MyException.new(arg.to_s) unless arg.is_a?(MyModel)

      # $! is a magic global variable holding the last raised
      # exception; Kernel#raise will also inject it as the 
      # cause attribute of the exception we construct here
      error_caught = $!
      msg = custom_message_for(arg, error_caught)

      ex = MyException.new(msg)
      # … any additional initialization goes here
      ex
    end

    private

    def custom_message_for(my_model_instance, error_caught)
      # …
    end
  end
end

This way, you can raise your custom exception normally, with a model instance instead of a string message, without having to remember to call new explicitly and upset RuboCop, as well as confusing Ruby programmers that come to your code later expecting the standard syntax.

begin
  my_model.frob
rescue => e
  raise MyException, my_model # works
end

raise MyException, 'some other reason' # also works

The message & initialization logic from MyException#exception could also go in a custom initializer, letting you just write MyException.new(arg, $!), but in that case make sure the initializer is smart enough to also handle a plain string message, and make sure it at some point calls super with a string message.

Related