Tao
Tao

Reputation: 2242

MQTT.js - How to handle connection errors?

I have difficulties detecting connection errors with MQTT.js.

I'm trying to use it in an Angular service and connecting and communicating with the server seems to work fine when the server is running but client.on('error', ...) never fires.

I managed to detect errors when connecting by attaching the error callback to client.stream instead, but stream seems to be a private property since it isn't exposed in the official TypeScript definitions, so not sure if this really is the correct way to go.

But what I still don't get to work are errors when the connection is lost, none of the error handlers fire. Instead the browser console logs unhandled websocket errors.

Sample code:

import { Injectable } from '@angular/core';
import { connect, MqttClient } from 'mqtt';
import * as msgpack5 from 'msgpack5';
import { environment } from '../../environments/environment';

@Injectable()
export class MqttService {

  private client: MqttClient;
  private msgpack: msgpack5.MessagePack;

  constructor() {
    this.msgpack = msgpack5();

    this.client = connect(`ws://${environment.host}:8001/mqtt`);

    this.client.on('connect', () => {
      console.log('connected');
      this.client.subscribe('foo');
    });

    this.client['stream'].on('error', (error) => {
      // fires when connection can't be established
      // but not when an established connection is lost
      console.log('stream', error);
      this.client.end();
    });

    this.client.on('error', (error) => {
      console.log('client', error); // never fires
    });

    this.client.on('message', (topic, payload) => {
      console.log(topic, this.msgpack.decode(payload));
    });
  }
}

Upvotes: 5

Views: 4785

Answers (1)

user11841320
user11841320

Reputation:

I had a very similar issue with client.on('error'.. didnt trigger on WebSocket connection error, the solution was:

client.stream.on('error', (err) => { console.log('error', err); client.end() });

Upvotes: 7

Related Questions