问题描述
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));
}
}
这是错误处理部分,我正尝试通过i18N Translations数组翻译错误消息
这是dto部分
@IsNotEmpty({message: "IsNotEmpty"})
@Apiproperty()
readonly firstName: string;
这是翻译json字符串
{
"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"
}
}
在这种特殊情况下,我在控制台中返回的消息与我传递的密钥相同 “ IsNotEmpty”
我在做什么错
解决方法
NeverMind,我解决了。 实际上问题是我正在将异步函数msg_validation的值提供给同步函数, 我也使catch异步了,并在函数调用之前添加了一个wait方法,并且像一个符咒一样工作