javascriptnode.jsnestjsnestjs-swaggernestjs-gateways

how to customise error message in post request?


I am using nest js for making Restfull Api . I am also using class-validator ,and class-transform to validate my request ot DTO. Currently It is showing this error

{"statusCode":400,"message":["username should not be empty","description should not be empty"],"error":"Bad Request"}

I want to customise this response like

{"statusCode":400,"message":["username is required","description is required"],"error":"Bad Request from user"}

is it possible in nestjs ??

here is my code https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts

I am using like that

import { IsNotEmpty } from 'class-validator';

export class UserDto {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  description: string;
}

in controller

 @Post('/create')
  @UsePipes(ValidationPipe)
  createUser(@Body() createTaskDto: UserDto): string {
    console.log('====');
    return 'jjjj';
  }

here is my code https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts

use API like that POST

https://9ziyr-5000.sse.codesandbox.io/create

Solution

  • With class-validator you can pass a message property to the validation decorator and change the error message. Something like this:

    import { IsNotEmpty } from 'class-validator';
    
    export class UserDto {
      @IsNotEmpty({ message: 'username is required' })
      username: string;
    
      @IsNotEmpty({ message: 'description is required' })
      description: string;
    }