Error Display Templates

In my code, I usually use the following setting:

module MyLib
  VERSION = "0.1.1"
  ERROR = [
    "You can either give one arg and a block or two args, not both.",
    "Yadda yadda..."
  ]
end

Then somewhere in my code:

def my_method(*args, &blk)
  raise(ArgumentError, MyLib::ERROR[0]) if (...condition snipped...)
end

Is there a better way to identify error messages?

+3
source share
1 answer

You can define your own exception classes:

module MyLib
  class FooError < ArgumentError
    def to_s
      "You can either give one arg and a block or two args, not both.",
    end
  end
end

Now if you pick it up:

raise MyLib::FooError
MyLib::FooError: You can either give one arg and a block or two args, not both.
    from (irb):46

And if you want to process it:

rescue MyLib::FooError
+7
source

All Articles