How to catch Sequelize Migration Errors and prevent adding migration to the SequelizeMeta table

1.2k views Asked by At

I've recently started to experiment with Sequelize Migrations using sequelize-cli. I noticed that if the migration script throws an error (using a try-catch block), sequelize-cli still updates the SequelizeMeta table with the migration as if it was successful.

What is the best way to catch errors and prevent Sequelize from entering the migration into the SequelizeMeta table on 'up', and conversely, prevent removing the migration when the 'down' script fails?

1

There are 1 answers

0
Anatoly On BEST ANSWER

Use a transaction to achieve rolling back all migration changes due to an exception like this:

    up: (queryInterface) => queryInterface.sequelize.transaction(
        async (transaction) => {
            await queryInterface.createTable(table, attributes, { transaction });
            if (some_condition) {
              throw new Error('Error while migrating');
            }
        }
),

Don't forget to indicate transaction in all Sequelize method calls.

Keep in mind that not all RDBMS support structure changes rolling back.