在 Sequelize 中不小心吞下了非空约束(可能是 bluebird 中的错误处理承诺搞砸了)

accidentally swallowing not-null constraint in Sequelize (probably error-handling in bluebird promises screwup)

(注意:可能是一个愚蠢的初学者问题),

我是 Sequelize 和 JS 中的 promises 的新手 --- 在测试一些我预计会抛出错误的代码的过程中,我看到了一个无声的失败。

这是相关代码(这是将 express 用于网络服务器,并在磁盘上使用 sqllite 后端)

const User = sequelize.define('user', {
  "firstName": {type: Sequelize.STRING},
  "lastName": {type: Sequelize.STRING},
  "id": {type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
  "gym": {type: Sequelize.STRING, allowNull: false}
});

function addUser(first, last, gym){
  return User.sync().then(() => User.create({"firstName": first, "lastName": last, "gym": gym}))
}

function testBlowUpAdd(req, res){
  addUser(null, null, null).then(res.send("added user")).catch(e => res.send(e.toString()));
}

app.get("/testboom", testBlowUpAdd);

当我到达那个端点时,我希望看到当您违反数据库约束时 Sequelize 抛出的任何错误。相反,我看到 "added user." 但是,当我查看数据库时,正如预期的那样,我的全空行没有出现。

很明显,我不小心吞下了错误。几乎可以肯定,因为我不明白承诺中的错误处理是如何发生的。我原以为对 addUser 的调用会抛出,结果承诺机制不会调用 then() 中的处理程序,而是会调用 catch() 中的处理程序...但显然这是不正确的?

设置 promise 时立即调用 res.send() 函数,res.send() 的 return 值作为参数传递给 .then()

.then 参数应该是一个函数,因此它可以 运行 稍后当 promise 解析时。

function testBlowUpAdd(req, res){
  addUser(null, null, null)
    .then(user => res.send("added user"))
    .catch(e => res.send(e.toString()));
}