Retry anything in PHP

Jan Machala
Nov 6, 2015 · 1 min read

Update: Read new post for more advanced conditional retry functions for PHP.

Just imagine that world, where any part of external resource never fail and you don’t need to care about this. Ok, come back to real world, where any kind of resource (connection, db, http request, cache, load/store …) may fail. I usually see in code something like this:

try {
$guzzle->get('http://....'); // call some resource
} catch (\TimeoutException $e) {
// do something with it ... maybe call one more?
$guzzle->get('http://....'); // just kidding ...

Normal solution is to fail and come back to user. My solution propose to be tolerant to failure and recover from that.

To retry function, just throw \RetryableException exception. Function could be generalized to catch just \Exception, but that leads to retry some cases which are supposed to fail.

If you saw that small statement goto… deal with it or provide me counterexample of shorter and readable code.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade