简体   繁体   中英

Callback of MQTT.js subscribe() function not capturing error message

I am using MQTT.js to subscribe to real time telemetry data.

client.on('connect', function () {  
    console.log('client connected');
    client.subscribe('flespi/state/gw/devices/' + flespi_id + '/telemetry/position', 
      { qos: 0 }, 
      function (err, granted){
        console.log(err.toString());
      }
   );      
}
=>client connected
=>Uncaught TypeError: err is null

Sometimes subscribe is unsuccessful so I use the callback function as indicated in the docs to retrieve the error.

I have on purpose given a wrong subscription token so even though it connects, it can't subscribe. The problem is that it says there is no error ( err is null ). So how can I know what the error is?

There is a similar question here, but for publish() instead of subscribe() : How to catch "access error" when publish inaccessible topic in mqtt.js?

Read the MQTT js docs carefully and read something about the actual MQTT messages too - ideally the standard itself or the nice interpretation at HiveMQ. The err callback parameter is for global failures, like transport layer errors. If the client sends a malformed topic name, or the client has insufficient permissions (this is exactly what HiveMQ mentions), you will find your failure as 0x80 code in the the granted array.

If the particular topic does not exist yet on the particular broker, that's not an error in MQTT. You may subscribe to wildcards, how the broker should handle that? Topic may start existing only when a first message is published to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM