Vis*_*agi 5 node.js typescript class-validator nestjs
我有一个 NestJs dto,看起来像这样
import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator';
import { AppService } from './app.service';
const restrictedNames = ['Name Inc', 'Acme Inc'];
class DTO {
@IsNotEmpty()
name: string;
@IsEmail()
email: string;
@IsNotEmpty()
@IsNotIn(restrictedNames)
orgName: string;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用一个异常过滤器,它返回错误,并提供有关验证失败的内容和哪个字段的清晰详细信息。
app.useGlobalPipes(
new ValidationPipe({
exceptionFactory: (validationErrors: ValidationError[] = []) => {
console.log(validationErrors);
return new BadRequestException({
statusCode: HttpStatus.BAD_REQUEST,
message: validationErrors.reduce((acc, error) => {
acc[error.property] = Object.keys(error.constraints).map(
(failed) => ({
failedValidation: failed,
message: error.constraints[failed],
}),
);
return acc;
}, {}),
error: 'validation',
});
},
}),
Run Code Online (Sandbox Code Playgroud)
);
它返回一个类似这样的错误
{"statusCode":400,"message":{"email":[{"failedValidation":"isEmail","message":"email must be an email"}],"orgName":[{"failedValidation":"isNotIn","message":"orgName should not be one of the following values: Name Inc, Acme Inc"}]},"error":"validation"}
Run Code Online (Sandbox Code Playgroud)
但对于失败的验证(例如@NotIn),我希望错误在保留关键字方面更加具体,并希望它们作为单独的键在错误中返回,例如:
{"statusCode":400,"message":{"email":[{"failedValidation":"isEmail","message":"email must be an email"}],"orgName":[{"failedValidation":"isNotIn","message":"orgName should not be one of the following values: Name Inc, Acme Inc", "data":{"reservedKeywords":["Name Inc","Acme Inc"]}}]},"error":"validation"}
Run Code Online (Sandbox Code Playgroud)
但是来自异常 Filter 的此块不会返回带有装饰器元数据的约束值。
message: validationErrors.reduce((acc, error) => {
acc[error.property] = Object.keys(error.constraints).map(
(failed) => ({
failedValidation: failed,
message: error.constraints[failed],
}),
);
return acc;
}, {}),
error: 'validation',
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
558 次 |
最近记录: |