I'm a programmer specialising in performant and scalable systems using PHP and Ruby and cooking


Published:
On Ruby

Ruby - retry on error

Ever wanted to be able to run a block of code and simply try it again if it fails? I have!

Take the scenario of attempting to POST somthing to a 3rd party API. We really must send our data however the API is flakey at best. What happens when it fails? Do we have to create some complex code and loops to attempt the POST again? NO! Ruby has a very handy built in feature for accompishing this.

retry allows the last block of code to be re-run (or retried :D). Combine this with Ruby's combined begin and method decleration to get very clean re-runnable methods:

def post_data(data ={})  
    Client.post(data)
rescue TimeoutError  
    retry
end  

Say we really wanted to post the data but didn't want to block our application, we could set a max number of tries:

def post_data(data = {})  
    tries ||= 3
    Client.post(data)
rescue TimeoutError  
    retry unless (tries -= 1).zero?
end  

Thanks to http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception-in-ruby/ for highlighting this feature on his blog