rfc:retry-keyword

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 number of 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) {
		die('Tried a bunch but failed.');
	}
}

Wrapping the recoverable 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) {
		retry;
	}
	die('Tried a bunch but failed.');
}

There are myriad use cases in which retry could be useful. The primary use case would be with temporary failed TCP/IP connections which are extremely common. Ideally apps would attempt to retry recoverable failures but it's currently not trial to do so scaring off a lot of developers from adding the retry logic. If were easier for developers to implement retry logic, we would see more stable apps as more developers adopt the easy-to-use syntax.

Backward Incompatible Changes

This RFC would not introduce and BC breaks.

Proposed PHP Version

Next PHP 7.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.

rfc/retry-keyword.1446584839.txt.gz · Last modified: 2017/09/22 13:28 (external edit)