1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 17:09:40 +01:00

Provide useful exception trace in TimeoutCancellationToken (#303)

Without this, the exception trace is pretty useless, because it only includes Loop::run() and other internal loop calls, giving absolutely no indication which kind of thing had a timeout.

Use debug_backtrace instead of creating the exception early, because it helps with the changes to GC behavior such a change might introduce.

Co-authored-by: Aaron Piotrowski <aaron@trowski.com>
This commit is contained in:
Niklas Keller 2020-04-04 17:05:26 +02:00 committed by GitHub
parent 8c486b40a8
commit feca077369
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 6 deletions

View File

@ -2,6 +2,8 @@
namespace Amp;
use function Amp\Internal\formatStacktrace;
/**
* A TimeoutCancellationToken automatically requests cancellation after the timeout has elapsed.
*/
@ -10,7 +12,7 @@ final class TimeoutCancellationToken implements CancellationToken
/** @var string */
private $watcher;
/** @var \Amp\CancellationToken */
/** @var CancellationToken */
private $token;
/**
@ -22,9 +24,12 @@ final class TimeoutCancellationToken implements CancellationToken
$source = new CancellationTokenSource;
$this->token = $source->getToken();
$this->watcher = Loop::delay($timeout, static function () use ($source, $message) {
$source->cancel(new TimeoutException($message));
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
$this->watcher = Loop::delay($timeout, static function () use ($source, $message, $trace) {
$trace = formatStacktrace($trace);
$source->cancel(new TimeoutException("$message\r\nTimeoutCancellationToken was created here:\r\n$trace"));
});
Loop::unreference($this->watcher);
}

View File

@ -3,26 +3,31 @@
namespace Amp\Test;
use Amp\CancelledException;
use Amp\Delayed;
use Amp\Loop;
use Amp\TimeoutCancellationToken;
use Amp\TimeoutException;
use function Amp\delay;
class TimeoutCancellationTokenTest extends BaseTest
{
public function testTimeout()
{
Loop::run(function () {
$line = __LINE__ + 1;
$token = new TimeoutCancellationToken(10);
$this->assertFalse($token->isRequested());
yield new Delayed(20);
yield delay(20);
$this->assertTrue($token->isRequested());
try {
$token->throwIfRequested();
} catch (CancelledException $exception) {
$this->assertInstanceOf(TimeoutException::class, $exception->getPrevious());
$message = $exception->getPrevious()->getMessage();
$this->assertContains('TimeoutCancellationToken was created here', $message);
$this->assertContains('TimeoutCancellationTokenTest.php:' . $line, $message);
}
});
}