Search code examples
node.jsnestjsnestjs-i18n

Nestjs and nestjs-i18n: Internationalization not working in Custom Exception Filter


I am trying to use an exception filter in my NestJS app. I have to translate my exception message into another language based on the request value. I have two languages file en and fr.

I have initialized i18N in my app.module.ts as per the following:

@Module({
  imports: [
   I18nModule.forRoot({
      fallbackLanguage: 'en',
      parser: I18nJsonParser,
      parserOptions: {
        path: path.join(__dirname, '/i18n/'),
      },
      resolvers: [
        PathResolver,
        { use: QueryResolver, options: ['lang', 'locale', 'l'] },
        AcceptLanguageResolver
      ]
    }),
  ],
  controllers: [AppController],
  providers: [AppService,
    {
      provide: APP_FILTER,
      useClass: NotFoundExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
      
    }
  ],
})
export class AppModule { }

My Exception filter class looks like this:

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {

  constructor(private readonly i18n: I18nService) { }

  async catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const statusCode = exception.getStatus();


    await this.i18n.translate('message.Unauthorized', { lang: 'fr' }).then(message => {
        console.log('message -> ', message);
        response.status(403).send({
                status: 6,
                message: message,
                data: null
              });  
      })
        

  }
}

I am throwing an exception from the LocalAuthGuard file:

@Injectable()
export class LocalAuthGuard implements CanActivate {
        canActivate(context: ExecutionContext,): boolean | Promise<boolean> | Observable<boolean> {
                const request = context.switchToHttp().getRequest().body;
                if(isEmpty(request.authkey)){
                        return false;
                }else{
                        return true;
                }
        }        
}

I have just put here my sample code from the project. When I run this project by some specific URL, I am not getting messages in the specific language. I am getting the following output in my console log.

message -> message.Unauthorized

It should return the message in fr language.

Can anybody help me, where am I going wrong?


Solution

  • I forgot to add the path in nest-cli.json. If we put the path in that file as below then the above code perfectly works fine.

    {
      "collection": "@nestjs/schematics",
      "sourceRoot": "src",
      "compilerOptions": {
        "assets": ["i18n/**/*","ssl/**/*"]
      }
    }