NestJS控制器和类验证器当前返回如下错误消息:
{
statusCode: 422,
message: [ 'Name is required', 'Email is required' ],
error: 'Unprocessable Entity'
}
但是我想将每条消息绑定到它的相关属性,像这样:
{
statusCode: 422,
message: { name: 'Name is required', email: 'Email is required' },
error: 'Unprocessable Entity'
}
我的DTO。
import { IsNotEmpty } from 'class-validator';
export class CreateUserRequestDTO {
@IsNotEmpty({ message: 'Name is required' })
name: string;
@IsNotEmpty({ message: 'Email is required' })
email: string;
}
我怎么能改变NestJS控制器/类验证器错误返回这样的消息?
可以通过将exceptionFactory
传递给ValidationPipe选项来修改验证错误的响应。
https://docs.nestjs.com/techniques/validation
参见示例实现:
app.useGlobalPipes(
new ValidationPipe({
exceptionFactory: (errors) => {
return new UnprocessableEntityException({
statusCode: 422,
error: 'Unprocessable Entity',
message: errors.reduce(
(acc, e) => ({
...acc,
[e.property]: Object.values(e.constraints),
}),
{},
),
});
},
}),
);