NestJS microservice class validator errors showing in docker container but not in API response

82 views Asked by At

I'm trying to show errors from my class validator in NestJS. This is actually the first time I'm using microservices and Nestjs (it's for a school project). I'm using Docker, and the errors are sent in my 'user' microservice container, but not showing in my API response. Is there a way to show them in my API response? I don't know why it's doing that.

My main.ts :

  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    validationError: { target: false, value: false },
    exceptionFactory: (validationErrors: ValidationError[] = []) => {
      return new RpcException(validationErrors);
    },
  }));

This is 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;
}

My user.service.ts :

  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';
      }
    }
  }

I send this to my API :

{
    "email" : "4",
    "password" : "pass"
}

In my container, it shows that it is actually validated :

\[Nest\] 89  - 11/25/2023, 8:43:55 PM   ERROR \[ExceptionsHandler\] Object:
[
  {
    "property": "email",
    "children": \[\],
    "constraints": {
      "isEmail": "email must be an email"
    }
  },
  {
    "property": "password",
    "children": \[\],
    "constraints": {
      "minLength": "password must be longer than or equal to 6 characters"
    }
  }
]

but my error is like this in postman :

{
  "statusCode": 500,
  "message": "Internal server error"
}

Sorry for the big post, I just want to provide as much code as possible for you to have some context.

I just have no idea what I should do to fix it, to be honest.

1

There are 1 answers

2
Jay McDoniel On

The RpcException you're sending back from the microservice is serialized to an Error inside the microservice gateway (the HTTP server reporting the Internal server error), because Nest, by default, treats plain Error instances as HTTP 500. If you want to actually return something like a 400 you'd need to catch the error from the microservice and properly translate it to an appropriate HTTP exception that Nest does understand