Skip to content

Commit 60ed314

Browse files
authored
Merge pull request #19 from async-interop/dedicated-error-handler
Add PromiseErrorHandler to decouple the specification
2 parents 4013918 + 8fc83b7 commit 60ed314

12 files changed

+251
-5
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/composer.lock
2+
/vendor/

.travis.yml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
language: php
2+
3+
php:
4+
- 5.4
5+
- 5.5
6+
- 5.6
7+
- 7.0
8+
- nightly
9+
- hhvm
10+
11+
matrix:
12+
allow_failures:
13+
- php: nightly
14+
fast_finish: true
15+
16+
cache:
17+
directories:
18+
- $HOME/.composer/cache
19+
20+
install:
21+
- composer install
22+
- composer show -t
23+
24+
script:
25+
- php vendor/bin/parallel-lint --exclude vendor .
26+
- php vendor/bin/phpunit --coverage-text

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ Any implementation MUST at least provide these two parameters. The implementatio
7272

7373
> **NOTE:** The signature doesn't specify a type for `$error`. This is due to the new `Throwable` interface introduced in PHP 7. As this specification is PHP 5 compatible, we can use neither `Throwable` nor `Exception`.
7474
75-
All registered callbacks MUST be executed in the order they were registered. If one of the callbacks throws an `Exception` or `Throwable`, it MUST be rethrown in a callable passed to `Loop::defer` so `Loop::onError` can be properly invoked by the loop. `Loop` refers to the [global event loop accessor](https://github.com/async-interop/event-loop/blob/master/src/Loop.php). The `Promise` implementation MUST then continue to call the remaining callbacks with the original parameters.
75+
All registered callbacks MUST be executed in the order they were registered. If one of the callbacks throws an `Exception` or `Throwable`, it MUST be forwarded to `Async\Interop\Promise\ErrorHandler::notify`. The `Promise` implementation MUST then continue to call the remaining callbacks with the original parameters.
7676

7777
If a `Promise` is resolved with another `Promise`, the `Promise` MUST keep in pending state until the passed `Promise` is resolved. Thus, the value of a `Promise` can never be a `Promise`.
7878

composer.json

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
11
{
22
"name": "async-interop/promise",
3-
"description": "Promise interface for implementing async operations",
3+
"description": "A promise interface for interoperability in async operations.",
44
"keywords": ["promise", "future", "awaitable", "async", "interop"],
55
"license": "MIT",
66
"require": {
7-
"php": ">=5.4"
7+
"php": ">=5.4.0"
8+
},
9+
"require-dev": {
10+
"phpunit/phpunit": "^4|^5",
11+
"jakub-onderka/php-parallel-lint": "^0.9.2",
12+
"jakub-onderka/php-console-highlighter": "^0.3.2"
813
},
914
"autoload": {
1015
"psr-4": {
11-
"Interop\\Async\\": "src/"
16+
"Interop\\Async\\": "src"
17+
}
18+
},
19+
"autoload-dev": {
20+
"psr-4": {
21+
"Interop\\Async\\Promise\\Test\\": "test"
1222
}
1323
}
14-
}
24+
}

phpunit.xml.dist

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<phpunit bootstrap="./vendor/autoload.php" colors="true">
2+
<testsuites>
3+
<testsuite name="Main Tests">
4+
<directory>./test</directory>
5+
</testsuite>
6+
<testsuite name="PHPT Tests">
7+
<directory suffix=".phpt">./test/phpt</directory>
8+
</testsuite>
9+
</testsuites>
10+
<filter>
11+
<whitelist addUncoveredFilesFromWhitelist="true">
12+
<directory>./src</directory>
13+
</whitelist>
14+
</filter>
15+
</phpunit>

src/Promise/ErrorHandler.php

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
namespace Interop\Async\Promise;
4+
5+
use Interop\Async\Promise;
6+
7+
/**
8+
* Global error handler for promises.
9+
*
10+
* Callbacks passed to `Promise::when()` should never throw, but they might. Such errors have to be passed to this
11+
* global error handler to make them easily loggable. These can't be handled gracefully in any way, so we just enable
12+
* logging with this handler and ignore them otherwise.
13+
*
14+
* If handler is set or that handler rethrows, it will fail hard by triggering an E_USER_ERROR leading to script
15+
* abortion.
16+
*/
17+
final class ErrorHandler
18+
{
19+
/** @var callable|null */
20+
private static $callback = null;
21+
22+
private function __construct()
23+
{
24+
// disable construction, only static helper
25+
}
26+
27+
/**
28+
* Set a new handler that will be notified on uncaught errors during promise resolution callback invocations.
29+
*
30+
* This callback can attempt to log the error or exit the execution of the script if it sees need. It receives the
31+
* exception as first and only parameter.
32+
*
33+
* As it's already a last chance handler, the script will be aborted using E_USER_ERROR if the handler throws. Thus
34+
* it's suggested to always wrap the body of your callback in a generic `try` / `catch` block, if you want to avoid
35+
* that.
36+
*
37+
* @param callable|null $onError Callback to invoke on errors or `null` to reset.
38+
*
39+
* @return callable|null Previous callback.
40+
*/
41+
public static function set(callable $onError = null)
42+
{
43+
$previous = self::$callback;
44+
self::$callback = $onError;
45+
return $previous;
46+
}
47+
48+
/**
49+
* Notifies the registered handler, that an exception occurred.
50+
*
51+
* This method MUST be called by every promise implementation if a callback passed to `Promise::when()` throws upon
52+
* invocation. It MUST NOT be called otherwise.
53+
*/
54+
public static function notify($error)
55+
{
56+
// No type declaration, because of PHP 5 + PHP 7 support.
57+
if (!$error instanceof \Exception && !$error instanceof \Throwable) {
58+
// We have this error handler specifically so we never throw from Promise::when, so it doesn't make sense to
59+
// throw here. We just forward a generic exception to the registered handlers.
60+
$error = new \Exception(sprintf(
61+
"Promise implementation called %s with an invalid argument of type '%s'",
62+
__METHOD__,
63+
is_object($error) ? get_class($error) : gettype($error)
64+
));
65+
}
66+
67+
if (self::$callback === null) {
68+
trigger_error(
69+
"An exception has been thrown from an Interop\\Async\\Promise::when handler, but no handler has been"
70+
. " registered via Interop\\Async\\Promise\\ErrorHandler::set. A handler has to be registered to"
71+
. " prevent exceptions from going unnoticed. Do NOT install an empty handler that just"
72+
. " does nothing. If the handler is called, there is ALWAYS something wrong.\n\n" . (string) $error,
73+
E_USER_ERROR
74+
);
75+
76+
return;
77+
}
78+
79+
try {
80+
\call_user_func(self::$callback, $error);
81+
} catch (\Exception $e) {
82+
// We're already a last chance handler, throwing doesn't make sense, so use a real fatal
83+
trigger_error(sprintf(
84+
"An exception has been thrown from the promise error handler registered to %s::set().\n\n%s",
85+
__CLASS__,
86+
(string) $e
87+
), E_USER_ERROR);
88+
} catch (\Throwable $e) {
89+
// We're already a last chance handler, throwing doesn't make sense, so use a real fatal
90+
trigger_error(sprintf(
91+
"An exception has been thrown from the promise error handler registered to %s::set().\n\n%s",
92+
__CLASS__,
93+
(string) $e
94+
), E_USER_ERROR);
95+
}
96+
}
97+
}

test/phpt/error_handler_001.phpt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
--TEST--
2+
ErrorHandler::notify() fatals without a handler
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::notify(new Exception);
9+
10+
?>
11+
--EXPECTF--
12+
Fatal error: An exception has been thrown from an Interop\Async\Promise::when handler, but no handler has been registered via Interop\Async\Promise\ErrorHandler::set. A handler has to be registered to prevent exceptions from going unnoticed. Do NOT install an empty handler that just does nothing. If the handler is called, there is ALWAYS something wrong.
13+
14+
%s in %s:%d
15+
Stack trace:
16+
#0 {main} in %s on line %d

test/phpt/error_handler_002.phpt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
--TEST--
2+
ErrorHandler::notify() does not fatal with a handler
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::set(function () { print "1"; });
9+
Interop\Async\Promise\ErrorHandler::notify(new Exception);
10+
11+
?>
12+
--EXPECT--
13+
1

test/phpt/error_handler_003.phpt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
--TEST--
2+
ErrorHandler::notify() fatals after handlers have been removed with ErrorHandler::set(null)
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::set(function () { print "1"; });
9+
Interop\Async\Promise\ErrorHandler::set(null);
10+
Interop\Async\Promise\ErrorHandler::notify(new Exception);
11+
12+
?>
13+
--EXPECTF--
14+
Fatal error: An exception has been thrown from an Interop\Async\Promise::when handler, but no handler has been registered via Interop\Async\Promise\ErrorHandler::set. A handler has to be registered to prevent exceptions from going unnoticed. Do NOT install an empty handler that just does nothing. If the handler is called, there is ALWAYS something wrong.
15+
16+
%s in %s:%d
17+
Stack trace:
18+
#0 {main} in %s on line %d

test/phpt/error_handler_004.phpt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
--TEST--
2+
ErrorHandler::notify() converts non-exception to exception
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::notify(42);
9+
10+
?>
11+
--EXPECTF--
12+
Fatal error: An exception has been thrown from an Interop\Async\Promise::when handler, but no handler has been registered via Interop\Async\Promise\ErrorHandler::set. A handler has to be registered to prevent exceptions from going unnoticed. Do NOT install an empty handler that just does nothing. If the handler is called, there is ALWAYS something wrong.
13+
14+
%SException%SPromise implementation called Interop\Async\Promise\ErrorHandler::notify with an invalid argument of type 'integer'%S in %s:%d
15+
Stack trace:
16+
#0 %s(%d): Interop\Async\Promise\ErrorHandler::notify(%S)
17+
#1 {main} in %s on line %d

test/phpt/error_handler_005.phpt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
--TEST--
2+
ErrorHandler::set() replaces the current handler
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::set(function () { print "1"; });
9+
Interop\Async\Promise\ErrorHandler::set(function () { print "2"; });
10+
Interop\Async\Promise\ErrorHandler::set(function () { print "3"; });
11+
Interop\Async\Promise\ErrorHandler::notify(new Exception);
12+
13+
?>
14+
--EXPECT--
15+
3

test/phpt/error_handler_006.phpt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
--TEST--
2+
ErrorHandler::notify() fatals if handler throws
3+
--FILE--
4+
<?php
5+
6+
require __DIR__ . "/../../vendor/autoload.php";
7+
8+
Interop\Async\Promise\ErrorHandler::set(function ($e) { throw $e; });
9+
Interop\Async\Promise\ErrorHandler::notify(new Exception);
10+
11+
?>
12+
--EXPECTF--
13+
Fatal error: An exception has been thrown from the promise error handler registered to Interop\Async\Promise\ErrorHandler::set().
14+
15+
%s in %s:%d
16+
Stack trace:
17+
#0 {main} in %s on line %d

0 commit comments

Comments
 (0)