Raise custom Exception with arguments

前端 未结 6 1778
礼貌的吻别
礼貌的吻别 2020-12-23 13:36

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 Exc

6条回答
  •  时光说笑
    2020-12-23 14:02

    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)
    

提交回复
热议问题