Seeking assistance with displaying validation errors in my NestJS project using class validator.
This is my first time working with microservices and NestJS, as it's for a school project. Errors from my 'user' microservice container are not appearing in the API response. How can I rectify this issue?
Below is a snippet from my main.ts
:
app.useGlobalPipes(new ValidationPipe({
transform: true,
validationError: { target: false, value: false },
exceptionFactory: (validationErrors: ValidationError[] = []) => {
return new RpcException(validationErrors);
},
}));
Here is a glimpse of my validation class user.dto.ts
:
import {
IsString,
IsEmail,
MinLength,
IsEnum,
IsOptional,
} from 'class-validator';
import { EnumRole } from '@lib/types/User';
export class UserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(6)
password: string;
@IsEnum(EnumRole)
@IsOptional()
role: EnumRole;
}
Part of my user.service.ts
for registering users:
async registerUser(userDto: UserDto) {
const hashedPassword = this.auth.send(
AuthMessage.HASH_PASSWORD,
userDto.password,
);
userDto.password = await firstValueFrom(hashedPassword);
userDto.role = EnumRole.USER;
const user = userDto as User;
try {
const newUser = await this.prisma.user.create({
data: user as UserSchema,
});
return formatUser(newUser) as User;
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
return 'Email already exists';
}
}
}
A sample JSON sent to my API:
{
"email" : "4",
"password" : "pass"
}
Validation occurs successfully in the container, but the error response in postman shows:
{
"statusCode": 500,
"message": "Internal server error"
}
I'm providing detailed code snippets for better understanding. Any guidance on resolving this issue would be appreciated.
Thank you for your support!