This is an old revision of the document!
PHP RFC: Retry keyword in catch blocks
- Version: 0.9
- Date: 2015-11-03
- Author: Sammy Kaye Powers, me@sammyk.me
- Status: Under Discussion
Introduction
The retry
keyword will make it easier to re-execute code blocks that failed due to recoverable errors.
PHP is primarily used for web apps and many times these apps need to communicate with 3rd-party services that can temporality fail with recoverable errors. Failures typically throw exceptions which can be captured in a try/catch
block. Once a recoverable error reaches a catch
block, it's not super trivial in user-land to retry the try
block.
This RFC proposes adding the retry
keyword in the catch
block to re-execute the try
block.
Proposal
Currently in order to retry a block of code that failed with a recoverable error in user-land, the developer needs to write quite a bit of bootstap code. There are a few ways to implement a feature that will retry a failed block of code x
times.
function myRetryFunction($maxTries) { try { somethingSketchy(); } catch (RecoverableException $e) { if ($maxTries === 0) { die('Tried a bunch but failed.'); } myRetryFunction(--$maxTries); } } myRetryFunction(5);
Wrapping recoverable failures in functions/closers is less than ideal. Let's try another method.
$maxTries = 5; for ($x=0; $x<=$maxTries; $x++) { try { somethingSketchy(); break; } catch (RecoverableException $e) { log('Fail'); } }
Wrapping code in for
loops is also less than ideal.
With the retry
keyword, the code becomes both easier to read and write.
$maxTries = 5; try { somethingSketchy(); } catch (RecoverableException $e) { if (--$maxTries === 0) { die('Tried a bunch but failed.'); } retry; }
There are myriad use cases in which retry
could be useful. The primary use case would be with failed TCP/IP connections due to temporary reasons which is extremely common. Ideally apps would attempt to retry recoverable failures but it's currently not trial to do so scaring a lot of developers away from retrying. If it's easy for developers to implement retry logic, we see more stable apps as more developers adopt the easy syntax.
Backward Incompatible Changes
This RFC would not introduce and BC breaks.
Proposed PHP Version
Next PHP 5.1.
Proposed Voting Choices
Requires a 2/3 majority.
Patches and Tests
There is no patch yet, but if approved, Sammy Kaye Powers will submit one.
Credits
Phil Sturgeon put me up to it. Blame him.