Ruby Error Handling Best Practices
Though the previous lesson on basic error handling is a good place to start, there is always room for improvement, and in this lesson, we are going to learn better error handling techniques in Ruby.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Though the previous guide walked through basic error handling that works in practice, there is always room for improvement. In this guide we are going to learn better error handling techniques in Ruby.

Sometimes, we may not want to rescue every error because we may actually be doing something wrong such as entering bad data into the database. In such cases we are better off rescuing only specific errors. For example, let's say you want 8/0 to proceed, but only want it to be logged so the system knows something like this happened.

To catch the error properly let's include our begin and rescue block, but this time, specify the error that needs to be rescued.

begin
  puts 8/0
rescue ZeroDivisionError => e
  puts "Error occurred: #{e}"
end

In this code, we are moving the description associated with ZeroDivisionError to the variable e, and printing it out like a normal variable.

If you execute this code, the output will be: Error occurred: divided by 0.

This format can be particularly useful when printing error messages to a log file, as it would give a better explanation of what went wrong that we can reference later on when performing debugging.

Let's try something else now. Change the code to puts nil + 10 instead of 8/0.

If you run this code, it gives the following error:

error_handling.rb:1:in `<main>': undefined method `+' for nil:NilClass (NoMethodError)

If you see, the application gives the NoMethodError which is exactly what it should be doing because nil is not a class defined for the + method.

Also, this error is not caught by the rescue block because we are asking it to catch only the ZeroDivisionError. To catch all standard errors, the code should be:

rescue StandardError => e

Now, if you run this code, the output will be:

Error occurred: undefined method `+' for nil:NilClass

This is definitely a more descriptive error message and it won't force the application to break.

devCamp Notes: It's important to keep in mind that the goal of error handling is not hiding errors, rather it is only for recording them so that you can fix the code implementation.