Home > Net >  NestJS with TypeORM - Catch PostgreSQL unique_violation error on save()
NestJS with TypeORM - Catch PostgreSQL unique_violation error on save()

Time:09-13

I have got a function in a service that needs to get a value of a new or already existing object from the database and save it.

Issue is that name attribute of this object needs to be unique.

I know i can just create a .some() function over all database objects to check if i can enter this new value but its probably very unoptimal.

I would like to create somethign like this (below) but i have no idea what to do next:

const newObject = await this.repository
      .save({
        ...newObjectDto,
      })
      .catch(err => {
        if (err instanceof QueryFailedError) {
          // some code for err checking to make 
          // sure i only catch the unique_violation 
          // error and then throw error
        }
      });

CodePudding user response:

Error code for unique_violation is 23505. You can check out the full list of error codes returned by PostgreSQL here.

In order to catch a unique constraint violation, you can do:

try {
  const newObject = await this.repository
    .save({
      ...newObjectDto,
    })
}
catch(err) {
  if (err instanceof QueryFailedError) {
    if(err.code === 23505) {
      console.log(`Unique constraint ${err.constraint} failed`);
      throw err;
    }
  }
}
  • Related