Ruby – Display error mode

In my code, I usually use the following settings:

module MyLib
VERSION = "0.1 .1"
ERROR = [
"You can either give one arg and a block or two args, not both.",
"Yadda yadda..."
]< br />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 define error messages?

You can define your own exception class:

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

Now, if you raise it:

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

If you want to deal with it:

rescue MyLib::FooError

In my code, I usually use the following settings:

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

and then somewhere in my code:

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

A good way to define the error message?

You can define your own exception class:

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

Now, if you raise it:

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

If you want to deal with it:

rescue MyLib::FooError

Leave a Comment

Your email address will not be published.