How to change the format of NestJS controller/class-validator error messages showing which field each message belongs to?

huangapple go评论59阅读模式
英文:

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),
          }),
          {},
        ),
      });
    },
  }),
);

huangapple
  • 本文由 发表于 2023年4月7日 00:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定