Muhammad Umer
Muhammad Umer

Reputation: 18097

How do you detect UniqueConstraintError in Sequelize?

I want to retry creating record in case unique attribute is already there, so how do I check if failure to create new record is due to UniqueConstraintError.

I'm trying to find an example code but haven't been able to find anything.

Upvotes: 2

Views: 3758

Answers (2)

Prashant Sharma
Prashant Sharma

Reputation: 877

import {UniqueConstraintError} from 'sequelize'

Model
.create({...})
.then(obj => {})
.catch(err => {
    if(err instanceof UniqueConstraintError){
        throw new Error('duplicate error')
    }
    else{
        throw err
    }
})

If you also need the field name (which caused this error) this might help

err.errors[0].path

Upvotes: 7

Dmytro Mysak
Dmytro Mysak

Reputation: 1252

Model.create(objectToCreate)
      .catch(sequelize.UniqueConstraintError, () => { // TODO });

If you use bulkCreate you can use boolean property in option ignoreDuplicates (not supported by Postgres) or updateOnDuplicate (only supported by MySQL)

Upvotes: 0

Related Questions