Blog

Tries - Solidify your code and retry on petty exceptions

I am always watching out for chunks of code that I seem to reuse in every new project and the "tries" pattern is definitely one of them. So finally I found some time to wrap it up into a gem and even come up with a nifty tagline:

Solidify your code and retry on petty exceptions

Keep trying

So what does it do? It basically lets you wrap some code with a try block to retry it a number of times when an exception is raised:

3.tries do
  Mechanize.new.get 'https://www.google.com/'
end

You can even define one or more exceptions that should be retried (all other ones will be ignored in that case):

3.tries on: Timeout::Error do
  Mechanize.new.get 'https://www.google.com/'
end

Or define a delay that should be waited for before each retry:

3.tries on: Timeout::Error, delay: 1.5 do
  Mechanize.new.get 'https://www.google.com/'
end

Perfect for implementing a poor man's API throttling!

I want it!

Add

gem 'tries'

to your Gemfile and start trying!

If you find any bugs or would like to see more features, file an issue or open a pull request in the project on Github!

Attribution

Now, I have to admit that I didn't come up with the idea myself. I found the snippet years ago and have been using and improving it ever since.

Neither do I remember where I found it nor who wrote it. I tried googling, without success. So if you are or know the original author of this snippet, please let me know in the comments and I'll add your name to it!

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!