1
0
mirror of https://github.com/danog/amp.git synced 2024-12-02 09:27:46 +01:00
amp/examples/exceptions/coroutine-try-catch.php

35 lines
881 B
PHP
Raw Normal View History

2017-09-20 14:47:32 +02:00
#!/usr/bin/env php
<?php
2017-09-20 17:50:00 +02:00
2017-09-20 14:47:32 +02:00
use Amp\Deferred;
use Amp\Loop;
require_once __DIR__ . "/../../vendor/autoload.php";
2018-06-18 20:00:01 +02:00
function asyncOperation()
{
2017-09-20 14:47:32 +02:00
$def = new Deferred();
Loop::delay(1000, function () use ($def) {
$def->fail(new Exception("force exception"));
});
return $def->promise();
}
try {
Loop::run(function () {
try {
2017-09-20 17:34:20 +02:00
// the failing promise returned from asyncOperation() will throw at the point of yield
// and can be caught like any other exception in PHP.
2017-09-20 14:47:32 +02:00
$res = yield asyncOperation();
echo "asyncOperation result -> " . $res . PHP_EOL;
} catch (Throwable $e) {
echo "asyncOperation catch -> " . $e->getMessage() . PHP_EOL;
}
});
} catch (Throwable $loopException) {
2017-09-20 17:34:20 +02:00
echo "loop bubbled exception caught -> " . $loopException->getMessage() . PHP_EOL;
2017-09-20 14:47:32 +02:00
}