英文:
How to change the format of NestJS controller/class-validator error messages showing which field each message belongs to?
问题
The NestJS controller, along with the class-validator, currently returns an error message like this:
{
statusCode: 422,
message: [ 'Name is required', 'Email is required' ],
error: 'Unprocessable Entity'
}
But I would like to bind each message to its related property like this:
{
statusCode: 422,
message: { name: 'Name is required', email: 'Email is required' },
error: 'Unprocessable Entity'
}
}
My DTO:
```typescript
import { IsNotEmpty } from 'class-validator';
export class CreateUserRequestDTO {
@IsNotEmpty({ message: 'Name is required' })
name: string;
@IsNotEmpty({ message: 'Email is required' })
email: string;
}
How could I change the NestJS controller/class-validator errors to return messages like this?
英文:
The NestJS controller, along with the class-validator, currently returns an error message like this:
{
statusCode: 422,
message: [ 'Name is required', 'Email is required' ],
error: 'Unprocessable Entity'
}
But I would like to bind each message to its related property like this:
{
statusCode: 422,
message: { name: 'Name is required', email: 'Email is required' },
error: 'Unprocessable Entity'
}
My DTO:
import { IsNotEmpty } from 'class-validator';
export class CreateUserRequestDTO {
@IsNotEmpty({ message: 'Name is required' })
name: string;
@IsNotEmpty({ message: 'Email is required' })
email: string;
}
How could I change the NestJS controller/class-validator errors to return messages like this?
答案1
得分: 5
The response for validation errors can be modified by passing exceptionFactory
to the ValidationPipe options.
查看示例实现:
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),
}),
{},
),
});
},
}),
);
英文:
The response for validation errors can be modified by passing exceptionFactory
to the ValidationPipe options.
https://docs.nestjs.com/techniques/validation
See example implementation:
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),
}),
{},
),
});
},
}),
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论