Skip to content

Commit

Permalink
Merge pull request #49 from clue-labs/error-handler
Browse files Browse the repository at this point in the history
Improve error reporting when custom error handler is used
  • Loading branch information
WyriHaximus committed Apr 19, 2022
2 parents 083fe4d + 502e3a3 commit 88c18df
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
16 changes: 12 additions & 4 deletions src/Buffer.php
Expand Up @@ -98,17 +98,25 @@ protected function handleResume()

protected function handleWrite($data, $remoteAddress)
{
$errstr = '';
\set_error_handler(function ($_, $error) use (&$errstr) {
// Match errstr from PHP's warning message.
// stream_socket_sendto(): Message too long\n
$errstr = \trim($error);
});

if ($remoteAddress === null) {
// do not use fwrite() as it obeys the stream buffer size and
// packets are not to be split at 8kb
$ret = @\stream_socket_sendto($this->socket, $data);
$ret = \stream_socket_sendto($this->socket, $data);
} else {
$ret = @\stream_socket_sendto($this->socket, $data, 0, $remoteAddress);
$ret = \stream_socket_sendto($this->socket, $data, 0, $remoteAddress);
}

\restore_error_handler();

if ($ret < 0 || $ret === false) {
$error = \error_get_last();
throw new Exception('Unable to send packet: ' . \trim($error['message']));
throw new Exception('Unable to send packet: ' . $errstr);
}
}
}
10 changes: 9 additions & 1 deletion tests/SocketTest.php
Expand Up @@ -86,7 +86,7 @@ public function testClientSendAfterEndIsNoop(Socket $client)
$this->loop->run();
}

public function testClientSendHugeWillFail()
public function testClientSendHugeWillFailWithoutCallingCustomErrorHandler()
{
$promise = $this->factory->createClient('127.0.0.1:12345');
$client = Block\await($promise, $this->loop);
Expand All @@ -95,7 +95,15 @@ public function testClientSendHugeWillFail()
$client->on('error', $this->expectCallableOnce());
$client->end();

$error = null;
set_error_handler(function ($_, $errstr) use (&$error) {
$error = $errstr;
});

$this->loop->run();

restore_error_handler();
$this->assertNull($error);
}

public function testClientSendNoServerWillFail()
Expand Down

0 comments on commit 88c18df

Please sign in to comment.