#How to we catch the connection exception for redis? I am using

5 messages · Page 1 of 1 (latest)

jade kite
#

How to we catch the connection exception for redis?
I am using this module https://www.npmjs.com/package/@nestjs-modules/ioredis

Here is my code:

  RedisModule.forRootAsync({
    imports: [SharedModule],
    inject: [ApiConfigService],
    useFactory: (configService: ApiConfigService) => ({
      type: 'single',
      url: configService.redisUrl,
    }),
  }),
split fox
#

Hey @jade kite do you need to add some logic when an error occurs?
If you just want to log the connection error, it's possible to inject the Redis Instance and attach an error listener

import { Redis } from 'ioredis';
import { Module, OnApplicationBootstrap } from '@nestjs/common';
import { InjectRedis, RedisModule } from '@nestjs-modules/ioredis';
import { ApiConfigModule } from './modules/api-config/api-config.module';
import { ApiConfigService } from '@modules/api-config/api-config.service';

@Module({
  imports: [
    ApiConfigModule,
    RedisModule.forRootAsync({
      inject: [ApiConfigService],
      useFactory: () => ({
        type: 'single',
      }),
    }),
  ],
})
export class AppModule implements OnApplicationBootstrap {
  @InjectRedis()
  private readonly client: Redis;

  onApplicationBootstrap() {
    this.client.on('error', (error) => {
      console.log('Redis error:', error);
    });
  }
}
jade kite
split fox
#

If this notification you want to send does not depend on an user request, you could use the same logic that I did, like injecting a service that will send the notification you want.
But if you need to send an http response for example containing the last Connection Error, you could try to connect again and catch the error or check the connection status

#
import { Module, OnApplicationBootstrap } from '@nestjs/common';
import { ApiConfigModule } from './modules/api-config/api-config.module';
import { InjectRedis, RedisModule } from '@nestjs-modules/ioredis';
import { Redis } from 'ioredis';

@Module({
  imports: [
    ApiConfigModule,
    RedisModule.forRootAsync({
      useFactory: () => ({
        type: 'single',
        options: {
          lazyConnect: true,
        },
      }),
    }),
  ],
})
export class AppModule implements OnApplicationBootstrap {
  @InjectRedis()
  private readonly redis: Redis;

  async onApplicationBootstrap() {
    // Try to connect to Redis
    try {
      await this.redis.connect();
    } catch (error) {
      console.error('Failed to connect to Redis', error);
    }

    // Or check the connection status
    if (this.redis.status !== 'ready') {
      console.log('Redis is not ready');
    }
  }
}