diff --git a/src/main.ts b/src/main.ts index 2e23c55..ff80913 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,7 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; -import { Logger } from '@nestjs/common'; +import { BadRequestException, Logger, ValidationPipe } from '@nestjs/common'; +import { ValidationError } from 'class-validator'; async function bootstrap() { const app = await NestFactory.create(AppModule); @@ -17,6 +18,31 @@ async function bootstrap() { credentials: true, origin, }); + app.useGlobalPipes( + new ValidationPipe({ + transform: true, + // https://stackoverflow.com/questions/75581669/customize-error-message-in-nest-js-using-class-validator + exceptionFactory: (validationErrors: ValidationError[] = []) => { + const errors = validationErrors.map((error) => ({ + error: Object.values(error.constraints).join(', '), + })); + + let errorMessage: string; + errors.forEach((value, index) => { + if (index == 0) { + errorMessage = value.error; + } else { + errorMessage = errorMessage.concat(', ', value.error); + } + }); + + return new BadRequestException({ + status: 'Validation Error', + message: errorMessage, + }); + }, + }), + ); await app.listen(process.env.PORT); }