K
K
klis2015-04-22 11:07:16
Yii
klis, 2015-04-22 11:07:16

How to catch ErrorException on fsockopen() error in Yii2?

I open the socket in the most usual way:

$socket = fsockopen("tcp://$hostname", $port, $errno, $errstr, 3);

I assume that if something is wrong (the port is closed, for example), then I want to inform the user about it. However, Yii2 has its own opinion on this matter and it crashes on this line, reporting an error:$socket == false

PHP Warning - yii\base\ErrorException

fsockopen(): unable to connect to tcp://<...> (Connection refused)

Trying to catch the exception does nothing. The result is exactly the same.
try {
  				$socket = fsockopen("tcp://$hostname", $port, $errno, $errstr, 3);
  				// do something
  				fclose($socket);
} catch(ErrorException $e) {
  // do nothing
}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
matperez, 2015-04-22
@klis

This is how it seems to work:

$errno = null;
        $errstr = null;
        try {
            $socket = fsockopen("tcp://127.0.0.1", 8085, $errno, $errstr, 3);
            fclose($socket);
        } catch(\ErrorException $e) {
            var_dump(get_class($e));
        }

I get string(23) "yii\base\ErrorException"
Check that you have an exception class with namespace specified "\ErrorException"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question