I am trying to change the behavior of the errors in NestJS. Currently when it is encountering an error, it is not just sending that error but it is still continuing the validation and displaying other errors as well. I want to display only one error. I want to change that behavior so that when it encountered first error it has to stop the validation and display that error only.
Here is the code :
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
app.useGlobalPipes(
new ValidationPipe({
stopAtFirstError: true,
}),
);
app.enableCors();
const port = configService.get('port');
await app.listen(port);
console.log(`Server is listening on port ${port}......`);
}
bootstrap();
user.controller.ts
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@HttpCode(HttpStatus.CREATED)
@Post()
create(@Body(ValidationPipe) createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
}
user.service.ts
@Injectable()
export class UsersService {
constructor(@InjectModel(User.name) private userModel: Model<User>) {}
async create(createUserDto: CreateUserDto) {
await this.userModel.create(createUserDto);
return {
status: 'sucess',
message: 'Successfully created',
};
}
}
create-user.dto.ts
export class CreateUserDto {
@IsNotEmpty({ message: 'id is required' })
@IsNumber({}, { message: 'Valid id is required' })
id: number;
@IsNotEmpty()
@IsString()
name: string;
@IsEnum(['INTERN', 'ENGINEER', 'ADMIN'], {
message: 'Valid role required',
})
role: 'INTERN' | 'ENGINEER' | 'ADMIN';
}
Api response
{
"message": [
"Valid id is required",
"name must be a string"
],
"error": "Bad Request",
"statusCode": 400
}
Here in the above response, i only want to show one error message in the "message": ["only one message"]
(or like this) "message": "Error message"
. It has to stop the validation when it encountered the first error. but currently it is not behaving like that. can anyone help.