I need to implement dto validation in nestjs micro-service a complete implementation of dto in nestjs TCP micro-service**strong text**
checkRemitter.dto.ts ```typescript import { IsNotEmpty, IsString } from 'class-validator'; export class checkRemitterDto { @IsNotEmpty() @IsString() readonly remitterNo: string; @IsNotEmpty() @IsString() userId: string } ``` app. controller ```typescript import {checkRemitterDto} from "./dto" @MessagePattern({ cmd: "checkRemitter" }) async checkRemitterData(data: checkRemitterDto) { try{ //some code }catch(error){ console.log(error) return new HttpException(error.response.data, error.response.status); } } ``` error=> BadRequestException: Bad Request Exception at ValidationPipe.exceptionFactory (/home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/common/pipes/validation.pipe.js:90:20) at ValidationPipe.transform (/home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/common/pipes/validation.pipe.js:66:30) at processTicksAndRejections (node:internal/process/task_queues:95:5) at resolveParamValue (/home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/microservices/context/rpc-context-creator.js:106:31) at async Promise.all (index 0) at pipesFn (/home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/microservices/context/rpc-context-creator.js:108:13) at /home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/microservices/context/rpc-context-creator.js:43:17 at /home/saranjith/Desktop/ECAPS/yesbank-dmtsor-service/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32 at ServerTCP.handleMessage (/home/saranjith/Desktop/ECAPS/yesbank-dmtsor-`enter code here`service/node_modules/@nestjs/microservices/server/server-tcp.js:62:54)`enter code here`
CodePudding user response:
Microservices use RpcException class. You can change ValidationPipe exception factory in main.ts And you should throw RpcException instead of http expception
main.ts
async function bootstrap() {
const microserviceApp = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
transport: Transport.REDIS,
// ...
});
// ...
microServiceApp.useGlobalPipes(new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
disableErrorMessages: true,
exceptionFactory: (errors) => {
return new RpcException(errors);
}
}));
// ...
}