3

The following has an on error event. How can I determine the specific error?

<?php
$loop = Factory::create();
$socket = new React\Socket\Server($loop);
$socket->on('connection', function (\React\Socket\ConnectionInterface $stream){

    $stream->on('data', function($rsp) {
        echo('on data');
    });

    $stream->on('close', function($conn) {
        echo('on close');
    });

    $stream->on('error', function($conn) use ($stream) {
        echo('on error');
        // How do I determine the specific error?
        $stream->close();
    });

    echo("on connect");
});

$socket->listen('0.0.0.0',1337);
$loop->run();
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

3

Looking at the implementation of a ConnectionInterface, React\Socket\Connection, it extends React\Stream\Stream, which uses emit() (which will trigger the callbacks registered with on): https://github.com/reactphp/stream/blob/c3647ea3d338ebc7332b1a29959f305e62cf2136/src/Stream.php#L61

$that = $this;
$this->buffer->on('error', function ($error) use ($that) {
    $that->emit('error', array($error, $that));
    $that->close();
});

Thus, the first argument of that function is the error, the second one the $stream:

$stream->on('error', function($error, $stream) {
    echo "an exception happened: $error";
    // $error will be an instance of Throwable then
    $stream->close();
});
bwoebi
  • 23,637
  • 5
  • 58
  • 79