Simple Retry Logic When Hitting Exceptions in Ruby
Yesterday I explored how to handle exceptions in Ruby. Sometimes though you might want to retry whatever code caused the exception. Take, for instance, the case where your code makes a call out to a Web service. There might be a network outage, and your code is unable to call out or the network is a bit flakey, and you know that after a number of retries your code will be able to reach the Web service.
In typical code you will want to wrap the ‘begin rescue’ or equivalent code in a loop and breakout of the loop after a few iterations if it is not successfully. Let’s take a look at the code that we will be working with.
Running this code will result in an exception being raised when you hit the following line of code:
resp = Net::HTTP.get_response(URI.parse(url))
So we learnt yesterday that we can ensure that the above code won’t come crashing down like a house of cards by wrapping it in a ‘begin rescue’ block. So that is exactly what we are going to do:
Great! The code will run now without falling over but what we are missing is some retry logic. Let’s add some logic to try this block of code three times before bailing out:
Now we have some code that will run four times and then exit and all the while being graceful about it. What more could a person want? Well isn’t there a way to make this code simpler and easier to understand? Glad you asked because yes there is a way:
Ok, what just happened? Well, we got rid of the ‘until’ loop; there is no need for that. A counter called ‘tries’ has been kept to keep track of how many times we have entered the ‘begin’ block. In the rescue block, we make a call to the retry statement that will re-execute the code in the ‘begin’ block whilst our ‘tries’ variable is less than three. The code and approach makes perfect sense, and the code looks great compared to using an ‘until’ loop.
It’s these small things about Ruby that makes it so appealing to me!