Monday, 23 August 2010

Using retry to run exception block again

One cool thing that I've not personally seen in another language is the retry keyword. If you use it in a rescue block, it'll rerun the block of code the exception occurred in.. Take a look at this code:

retry_count = 0
begin
  ShoddyWebService.new.call
rescue Timeout::Error => ex
  retry_count += 1
  raise ex if retry_count > 5
  puts "Shoddy web service timed out..retry #{retry_count}/5"
  retry
end

Now, if your web service call fails 5 times, the code will fail. This makes your applications more resilient to external problems, as services timing out does happen once in a while.. I'd rather my application handled that nicely instead of just bombing out.

1 comment:

  1. This is great Mike!!!
    Would be great to extend this into calling a sleep to wait a while before retrying...

    ReplyDelete