It's easy to create your own exceptions in Ruby. Just follow these steps:
1. Make a New Class
Exceptions are classes, just like everything else in Ruby! To create a new kind of exception, just create a class that inherits from StandardError, or one of its children.
class MyError < StandardError
end
raise MyError
By convention, new exceptions have class names ending in "Error". It's also good practice to put your custom exceptions inside a module. That means your final error classes will look like this: ActiveRecord::RecordNotFound
and Net::HTTP::ConnectionError
.
2. Add a message
Every ruby exception object has a message attribute. It's the longer bit of text that's printed out next to the exception name
Example of an exception's message attribute
You can specify a message when you raise an exception, like so:
raise MyError, "My message"
And you can add a default message to your custom error class by adding your own constructor.
class MyError < StandardError
def initialize(msg="My default message")
super
end
end
3. Add a custom data attributes to your exception
You can add custom data to your exception just like you'd do it in any other class. Let's add an attribute reader to our class and update the constructor.
class MyError < StandardError
attr_reader :thing
def initialize(msg="My default message", thing="apple")
@thing = thing
super(msg)
end
end
begin
raise MyError.new("my message", "my thing")
rescue => e
puts e.thing # "my thing"
end
That's it! Creating a custom error or exception in Ruby really isn't that difficult. There is one thing to be aware of. Notice how we always inherited from StandardError in the examples? That's intentional. While there is an Exception class in Ruby, you should NEVER EVER inherit directly from it. For more information about this, check out our article about the differences between Exception and StandardError