Search code examples
try-catchnestjstypeorm

NestJS TypeORM multiple error handling username and email conflict


How should we handle multiple duplicate fields in an TypeORM + Nest server?

Specifically username and/or email field duplication constraint in an TypeORM Entity?

It would be good to handle duplication of these fields in the same try/catch method or error handler.


Solution

  • First, NestJs automatically catches all exceptions so no need to explicitly use try-catch block inside nest application unless you are calling a third party API, you can read more about it here. So, even if you don't use try catch block nest will catch all exceptions thrown by the database.

    Second, It is still a bad practice because it is better to handle all cases where you expect database to throw error. Since, here you know that database will throw error if duplicate data is inserted then handle those cases before it reaches the database. What I mean by that is:

    • Before inserting check whether that data is already present in database or not.
    • If it's already there then return a Bad Request exception.
    • If not, then insert the data.

    Example: Create new User API.

    async createUser(createUserDto: CreateUserDto): Promise<CreateUserRO> {
        const { phone } = createUserDto;
        const existingUser = await this.userRepository.findOne({
          phone,
        });
    
        if (existingUser) {
          throw new HttpException(
            'Phone number already exists',
            HttpStatus.BAD_REQUEST,
          );
        }
    
        const user = new User(createUserDto);
        await this.userRepository.persistAndFlush(user);
    
        return new CreateUserRO(true, user.id);
    }