Tony Guinta
Tony Guinta

Reputation: 653

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

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?

Upvotes: 2

Views: 1392

Answers (1)

Anatoly
Anatoly

Reputation: 22803

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.

Upvotes: 2

Related Questions