How to Handle an Exception and Retries in Ruby on Rails
Ruby allows you to handle an exception when you want to recover from an error in your application. This is important if you decide to gracefully exist form the program without system generated error message being presented to the UI.
Rescue is one such method in Ruby. It is used with begin/rescue code block.
def error_handled
begin
puts “my text”
raise
rescue
puts “no problem”
end
end
The code will continue executing after rescue so that your program can run uninterrupted even if there is an error in the middle of it.
A rescue method always deal with exceptions of the StandardError class or it’s subclasses. You can rescue a specific class by mentioning it as well.
def error_handled
begin
puts “my text”
raise
rescue SyntaxError
puts “no problem”
end
end
a rescue clause also allows you to stack up Exceptions to be rescued in your code.
begin
rescue SyntaxError
rescue SystemError
end
Exception handling lets you view an exception details after you rescue method is called. Here is an example how Ruby does in code.
begin
raise ‘An error’
rescue Exception => e
puts e.message
end
Alternatively, you can use $! Notation to output most recent exception that occurred.
begin
raise ‘An error’
rescue Exception
puts $!.message
end
The later method is not recommended due to global nature of $! Notation.
You can also retry an exception within rescue clause so that code can re-execute the line that gave an error in a first place in hope that error was a result of network connection drop or something similar in nature. You can see from the example below that you can call retry method right after rescue.
begin
raise ‘An error’
rescue Exception => e
puts e.message
retry
end
It is the same method Ruby check_connection method uses for retrying database connection certain number of times before giving up on it completely.
require “open-uri”
def check_url(max=3,url=”http://www.google.com”)
tries = 0
begin
tries+=1
open(url)
rescue Exception
retry unless tries >= max
end
end