Node.js 当错误抛出时,Sequelize事务不执行回滚
我使用的是sequelize事务(托管),当错误抛出回滚并没有真正发生时,可能我在这里做错了什么 我的测试用例:当代码块2抛出错误时,代码块1中完成的事情不会回滚,请帮助Node.js 当错误抛出时,Sequelize事务不执行回滚,node.js,sequelize.js,Node.js,Sequelize.js,我使用的是sequelize事务(托管),当错误抛出回滚并没有真正发生时,可能我在这里做错了什么 我的测试用例:当代码块2抛出错误时,代码块1中完成的事情不会回滚,请帮助 return sequelize.transaction(function (t) { return db.VenueTag.destroy({where: {venueId: venue.venueId}}, {transaction: t}).then(function () { }, {t
return sequelize.transaction(function (t) {
return db.VenueTag.destroy({where: {venueId: venue.venueId}}, {transaction: t}).then(function () {
}, {transaction: t}).then(function () {
//block 1
return db.VenueTag.upsert({
...
});
}, {transaction: t}).then(function () {
//block 2
//update venue details
return venue.updateAttributes({
...
},{ transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
return res.status(200).json(result);
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
});
您的承诺链中有错误,请尝试以下方法:
return sequelize.transaction(function (t) {
return db.VenueTag.destroy({where: {venueId: venue.venueId}}, {transaction: t})
.then(function () {
//block 1
return db.VenueTag.upsert({
...
}, {transaction: t});
.then(function () {
//block 2
//update venue details
return venue.updateAttributes({
...
},{ transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
return res.status(200).json(result);
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
});
如果您正在迎合ES7受众或使用node.js。您可以使用异步/等待方法简化回调/承诺链:
/*Global Setup*/
let venue, db; // Whatever instances these are....
async function deleteVenueTag () {
let transaction;
try {
transaction = await sequelize.transaction();
let VenueTag = await db.findOne({where: {venueId: venue.venueId}}, {transaction});
if (VenueTag) {
await VenueTag.destroy({ transaction });
await VenueTag.upsert({ transaction });
await venue.updateAttributes({ transaction });
await transaction.commit();
}
} catch (error) {
transaction.rollback();
}
}
如果您正在使用下面类似的内容
return Users.update(updateUser, {
where: {
uid: sessionUser.uid,
status: 'ACTIVE'
},
transaction: t //second parameter is "options", so transaction must be in it
})
然后,transaction是第二个options参数中的一个键,而不是第三个如果您认为这是一个续集错误,那么它可能更适合于第二个选项参数。还记得将模型定义发布到Bugjan。。问题登录sequelize bug tracker.caution,如果找不到任何结果,findOne将返回null,因此在这种情况下将抛出。。。无法销毁空错误。回滚是在一个catch block中自动完成的我相信这是一个bug,我现在看到它是一个bug,我一直在使用它,记住findOne在不匹配任何记录的情况下返回null,而不知道这是一个bug,很好。。。。我的第一个方法实际上是极限为1的findAll