Search code examples
nestjsnestjs-microservice

NestJS microservices: catch broker disconnection


In express-based applications, we can catch the broker error as following:

mqttClient.on('reconnect', () => {
    console.log('reconnecting...');
    // notify to sentry
})

How do we handle such a thing in NestJS?


Solution

  • Finally I found the solution. The way is to use a custom strategy that extends the built-in transporter. Example::

    import { ServerMqtt } from '@nestjs/microservices';
    import { MqttClient } from '@nestjs/microservices/external/mqtt-client.interface';
    
    class MyCustomStrategy extends ServerMqtt {
      bindEvents(mqttClient: MqttClient) {
        super.bindEvents(mqttClient);
        mqttClient.on('reconnect', () => console.log('Reconnecting...'));
      }
    }
    
    // and later
    const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
      strategy: new MyCustomStrategy({
        url: 'mqtt://0.0.0.0:1883',
      }),
    });