node.js - NestJs - Class-validator 未返回完整的驗證錯誤對象
我在 NestJS 中使用 class-validator 來建立像這樣的驗證:
export class LoginDTO {
@IsEmail()
@MinLength(4)
email: string;
@IsNotEmpty()
@MinLength(4)
password: string;
}
它有效,但不是預期的效果。返回的物件看起來像這樣:
{
"statusCode": 400,
"message": [
"email must be longer than or equal to 4 characters",
"email must be an email"
],
"error": "Bad Request"
}
我希望它包含像這樣的所有資訊:
{
"statusCode": 400,
[{
target: /* post object */,
property: "title",
value: "Hello",
constraints: {
length: "$property must be longer than or equal to 10 characters"
}]
"error": "Bad Request"
}
如何返回所有缺失的屬性?
答案#1
這是在 Nestv7 中的一個重大變更。根據遷移指南,使用 ValidationPipe 時,你可以像這樣傳遞一個 exceptionFactory 屬性
exceptionFactory: (errors) => new BadRequestException(errors),
它應該會給你想要的東西。
