Learn the ins and outs of error handling with Ruby on Rails in our comprehensive tutorial, covering a range of topics such as handling errors, raising errors, and dealing with different types of errors.
This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this Ruby on Rails tutorial:
Handling errors, Different types of errors, The raise method
Exercise Overview
In this exercise, we’ll be looking at error handling and exceptions in Ruby. Unfortunately, sometimes things go awry in our code and it’s best to be prepared. Let’s take a brief tour of Ruby’s robust error handling system.
Handling Errors
First and foremost, we should learn how to make sure our application doesn’t come crashing down just because some trifling error occurs.
If Interactive Ruby isn’t running, go to/open Terminal and type the
irb
command.-
In Terminal, type:
puts doggerel
Terminal will return an error:
NameError (undefined local variable or method 'doggerel' for main:Object)
because this variable doesn’t exist. If this happened on our site while a user was browsing a page, they may see an error message rather than the page. This error would not be that important to the operation of our site, so we could just print nothing and move on, rather than show the error. -
As it happens, Ruby provides us with controls for this. Add the following
begin...end
loop:begin puts doggerel rescue puts "No doggerel today!" end
rescue
specifies what happens if an error occurs. Now our users won’t see an error, just the message we specified. In a real-world situation, we might use this structure to print a user-friendly error message on the screen, or, in the case of a more minor problem, we might not show the user anything, but instead quietly log it in the back-end for later review.If you know the type of error you want to anticipate, you can use
rescue
to reference that error explicitly. Notice that when we first typed puts doggerel, we got a NameError. -
Let’s see another type of error in Ruby. Type the following:
2 + '2'
Terminal will return a
TypeError
. You may remember this from Rails Level 1 where we also tried to add a string to an integer and Ruby got confused. -
Let’s try putting both types of errors together to see how we can use
rescue
to handle different errors in different ways. Create a new method:def should_break begin yield
We’re going to pass a block (a bit of executable code) that has errors in it. yield executes the code.
-
Next specify what will happen in the case of a
NameError
:rescue NameError puts "No such variable exists."
-
Then specify what will happen in the case of a
TypeError
:rescue TypeError puts "Mismatch of variable types." end end
-
Call the method and pass it a block:
should_break { puts doggerel }
The NameError should appear:
No such variable exists.
-
Type the following:
should_break { 2 + '2' }
The TypeError should appear:
Mismatch of variable types.
Raising Errors
Sometimes we need to raise our own errors when something doesn’t work in the code. As an example, let’s steer clear of copyright issues when naming our users.
-
To initialize the user with a name, type:
class User attr_accessor :name def initialize(name)
-
Now we’ll raise another exception (error) that comes with Ruby. Type the following
ArgumentError
as shown below:raise ArgumentError, "Name is copyrighted" if name == 'Mickey Mouse' @name = name end end
The
raise
method’s syntax is very simple. It tells Ruby to throw an error and stop executing the program unless there’s some rescue code that handles the error appropriately. -
Create a new student:
u = User.new("Jamie")
-
Check if the new student’s name has been assigned:
u.name
Terminal should return:
"Jamie"
-
Try to create a new student called Mickey Mouse:
u = User.new("Mickey Mouse")
Terminal should return:
ArgumentError: Name is copyrighted
(If you are wondering why we picked that type of exception, it’s because the name is an argument. When we sent the name Mickey Mouse, it was an invalid argument.) -
Check the new student’s name again:
u.name
Terminal should still return
"Jamie"
because execution was stopped and the name Mickey Mouse was not assigned. -
If you need to create a new exception type, you can do so by subclassing
RuntimeError
(RuntimeError is the default for raise). Type the following:class CopyrightError < RuntimeError end
You don’t actually have to put anything in the class—simply creating it is good enough.
-
Now raise CopyrightError:
raise CopyrightError, "Name is copyrighted"
Congratulations, you’ve got a
CopyrightError
! Close the Terminal window, and if prompted click Terminate.