php-mqtt/client

PHP Fatal error: Uncaught PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException

jacksnodgrass opened this issue · 3 comments

Maybe less of a php-mqtt issue and more of a php exception issue..... or not..... maybe a doc update?

I know WHY I am getting:
PHP Fatal error: Uncaught PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException: [1000] Establishing a connection to the MQTT broker failed: Socket error [113]: No route to host in

... how to I CATCH that error? I don't want the program to just bomb...

try {
	$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
} catch(<what goes here> $e) {
	print "error: mqtt->connect() Failed!\n";
	exit;
}

I've tried a few different things for the <what goes here> part of the catch...

it's not: \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException and it's not: Exception

just not sure what the answer is.... Does anyone know?

I want to programmaticly exit the program with a nice error message or maybe fallback to a 2nd server to connect to.... I don't want the program to end and give me a stack trace.....

You are catching the exception at the wrong place. The $mqtt->connect() method is throwing the exception. Make sure to wrap the other MQTT client method calls also in the try-catch:

try {
    $mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
    $mqtt->connect();
} catch(\PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException $e) {
    print "error: mqtt->connect() Failed!\n";
    exit;
}

OK.... that worked.... thanks. Maybe adding that to the example script will help someone else down the line.... maybe...

The examples do all contain proper exception handling. It is also part of the exception text that Establishing a connection to the MQTT broker failed, so I think it's obvious enough to be honest...