1

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?

  • If I had to take a guess, your `i18n` directory isn't being moved to the `dist` on compilation, so `__dirname + '/i18n/'` for the path option isn't working as expected. Can you show the directory structure of `src` and `dist`? – Jay McDoniel Aug 27 '21 at 16:21

1 Answers1

1

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/**/*"]
  }
}
  • The i18n directory exists in the dist directory. But the problem is about the order of running modules. The PolicyGuard prevents run resolver to detect the requested language. – JahangirAhmad Feb 20 '22 at 08:02