Translating Class Validation error message using i18n library in NestJs project

Viewed 3761
import {
  Catch,
  HttpException,
  ExceptionFilter,
  ArgumentsHost,
} from "@nestjs/common";
import { Response } from "express";
import { ResponseError } from "../common/dto/ResponseDto";
import { I18nService } from "nestjs-i18n";


@Catch(HttpException)
export class ExceptionResponseFilter implements ExceptionFilter {

  constructor(
    private readonly _i18n: I18nService
) {}
async msg_validation(msg_key: string): Promise<string> {
    const validation = await this._i18n.translate(
        "translations.validation_messages."+msg_key,
        {
            lang: "en",
        }
    );
    return validation;
   }

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    const r = <any>exception.getResponse();

    let message: string;
    if (exception.message) {
      console.log(r);
      message = typeof r.message == "string" ? r.message : this.msg_validation(r.message[0]);
    } else {
      message = `Unknown error occured!`;
    }
    response.status(status).send(new ResponseError(message, null, status));
  }
}

this is the error handling part and i m trying to translate the error message via i18N translations array

this is the dto part

@IsNotEmpty({message: "IsNotEmpty"})
    @ApiProperty()
    readonly firstName: string;

and this is the translation json string

{
    "keywords": {
        "admin": "Administrator"
    },
    
    "validation_messages": {
            "IsString": "Should be a String",
            "IsNotEmpty": "Should not be Empty",
            "IsUnique": "Already Exists",
            "MaxLength": "Should not be Greater than",
            "MinLength": "Should not be Less than",
            "IsNumberString": "Should not Contain Alphabets or Special Characters",
            "IsPhoneNumber": "Should be a Valid Phone Number",
            "IsAlpha": "SHould not Contain Numbers or Special Symbols",
            "IsEmail": "Should be a Valid Emial Format"
        }
    
}

the message i m getting back in console in this particular case is same as the key i m passing "IsNotEmpty"

What am i doing wrong

1 Answers

NeverMind, i Solved it. Actually the problem was that i was feeding the value of an async function msg_validation to a sync function, i Made the catch async as well and added await method before the function call and worked like a charm

Related