如何根据 @Column({ unique: true }) 装饰器失败的字段写入错误。错误代码 23505

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

我正在尝试编写一个注册异常,让用户知道他们的用户名或电子邮件是否已被使用。使用装饰器 @Column({ unique: true}) 允许我捕获错误 23505,但无论是用户名还是电子邮件失败,它都是相同的错误。有没有一种方法可以确定我在哪个属性上捕获错误并为每个属性编写一个单独的异常?

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

您应该检查此代码。如果要将错误分开,则需要同时检查两者。我不确定您使用的是 typeORM。我在此代码中使用了 TypeORM。

    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();
      }
    }