I have now coded many apps that uses SOAP, Rest and normal HTTP/Regex-parsing. The problem in many of these apps, is that the system I am communicating with sometimes timeouts or returns invalid XML, which makes my scripts crash or at least very sad.
I then came up with a very handy-retry class, which implements the Timeout-class from Ruby’s standard-lib and extends it with being able to retry the given operating catching specific or all exceptions.
The problem is that every time you just want et to retry your code-block, you have to write a whole new loop, keep count of the times you have retried, implement the timeout-functionality, and even though this is properly between 10 to 20 lines of code in Ruby, it is very annoying – and lets face it, you should not write the same code three times.
To use this retry-functionality, you can do something like this:
count = 0
Knj::Retry.try(:tries => 5, :timeout => 3, :errors => [RuntimeError]) do
count += 1
print "Try #{count.to_s}\n"
raise "Test"
end
In my opinion the script pretty much speaks for itself. It will try to run the block 5 times, if the block takes more than 3 seconds to execute it will try again, if the block raises an error of the class RuntimeError, it will be caught and the block will then be tried again.
It it hits the maximum executions, the exception will actually be thrown and not caught. If “:errors” is not given, it will catch all errors except Interupt and SystemExit (though you can give it a :exit => false to not catch the SystemExit).
This way of handling retries and timeouts makes it much more safe for me to write SOAP-, Rest- and HTTP/Regex-parsing scripts – and have drastically reduced my error reports from these scripts to almost zero.
If you want to have look at the code the Knj::Retry-class, visit “knjrbfw” at Github.com here: