- Read Tutorial
- Watch Guide Video
In this guide let's wind up error handling in Ruby. In the previous guides we first looked at the basic error handling syntax and followed that up with a better way to manage errors effectively. In this guide we are going to see how we can handle errors in a production application.
We are going to create a method called error_logger
. This method will be responsible for appending all the errors that occur in our program into a log file. Let's create a file called error_log.txt
. It's an empty file to which we will be adding more data.
This is what our error_logger
method will look like:
def error_logger (e) File.open('error-handling-lessons/error_log.txt', 'a') do |file| file.puts e end end
In this code, we are opening the error_log.txt
file in append mode and printing the error message into it. This method takes error as its parameter, and puts it into the file.
Next, let's begin our main program code.
begin puts nil + 10 rescue StandardError => e error_logger("Error: #{e} at #{Time.now}") end
If you execute this file, there will be no output visible on the terminal, but open the error_log.txt
file, and you can see the error message in it.
Error: undefined method `+' for nil:NilClass at 2016-09-05 18:13:29 -0500
Now, let's switch up the error by adding the following code in the begin
portion of the program:
puts nil * 10
Execute the code and open your log file. You can see that our error log file now has multiple data items:
Error: undefined method `+' for nil:NilClass at 2016-09-05 18:13:29 -0500 Error: undefined method `*' for nil:NilClass at 2016-09-05 18:14:09 -0500
Let's now attempt to run a divide by 0 operation.
puts 8/0
And the error file should have this message appended as well, along with the timestamp of the error.
Error: undefined method `+' for nil:NilClass at 2016-09-05 18:13:29 -0500 Error: undefined method `*' for nil:NilClass at 2016-09-05 18:14:09 -0500 Error: divided by 0 at 2016-09-05 18:14:59 -0500
So, this is a practical way of handling errors in a real-world program.