Search code examples
typescriptpostgresqlerror-handlingnestjstypeorm

How to write error depending on field in which the @Column({ unique: true }) Decorator failed. Error Code 23505


I am trying to write a Sign Up exception to let the user know if their username OR email was already in use. Using the decorator @Column({ unique: true}) allows me to catch the error 23505, but it is the same error regardless of whether it is the username or email that fails. Is there a way I can determine which of the properties I am catching the error on and write a separate exception for each?

  const user = this.create({
      username,
      email,
      password: hashedPassword,
    });
    try {
      await this.save(user);
    } catch (error) {
      console.log(error.code);
      if (error.code === '23505') {
        throw new ConflictException('Username already exists');
      } else {
        throw new InternalServerErrorException();
      }
    }
@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ unique: true })
  username: string;

  @Column({ unique: true })
  email: string;

  @Column()
  password: string;
}

Solution

  • You should check this code. If you want to separate the error, you need to check it both. I'm not sure you are using typeORM. I'm using a TypeORM in this code.

        const user = this.create({
          username,
          email,
          password: hashedPassword,
        });
        try {
          // check if there is same username
          const findName = await this.findOne({
            username : username
          })
          // if the username exist, throw a error
          // if not, it will be 'undefined'
          if(findName){
            throw new ConflictException('Username already exists');
          }
    
          // check if there is same email
          const findEmail = await this.findOne({
            email : email
          })
          // if the email exist, throw a error
          // if not, it will be 'undefined'
          if(findEmail){
            throw new ConflictException('Email already exists');
          }
    
          await this.save(user);
        } catch (error) {
          console.log(error.code);
          if (error.code === '23505') {
            throw new ConflictException('Username already exists');
          } else {
            throw new InternalServerErrorException();
          }
        }