我试图将this method用于非顺序承诺输出。
快速.json调用成功地从API发送201和用户对象,但在控制台中,我得到如下所示的未处理拒绝错误。这似乎应该被控制器中的.catch处理程序捕获。我想知道为什么会发生这种情况?
UserController中
module.exports.postUser = function (req, res, next) {
var user = req.body.user;
var ip = req.ip;
userService.createUser(user, ip)
.then(function (user) {
res.status(201).json({"user": user.toJSON()});
})
.catch(function (err) {
return next(err);
});
};
userService
module.exports.createUser = function (user, ip) {
var user = new Promise(function (resolve, reject) {
return resolve(User.forge(user));
});
return user.then(function validateUser(user) {
return user.validate({validatePassword: true});
})
.then(function hash() {
var password = user.value().get('password');
return hashPassword(password);
})
.then(function setPassword(hashedPass) {
user.value().set('hashedPass', hashedPass);
return user.value().save();
})
.then(function () {
return user;
});
};
输出
Unhandled rejection error: null value in column "status" violates not-null constraint
at Connection.parseE (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
From previous event:
at Client._query (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/dialects/postgres/index.js:122:12)
at Client.query (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/client.js:127:24)
at Runner.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:118:24)
From previous event:
at /Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:44:21
From previous event:
at Runner.run (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:30:20)
at QueryBuilder.Target.then (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/interface.js:27:43)
at null.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/bookshelf/lib/model.js:208:36)
at processImmediate [as _immediateCallback] (timers.js:367:17)
答案 0 :(得分:2)
最可能的原因是return user.value().save()
没有返回一个promise,而是实现了回调。如果是这种情况,那么错误将被抛出本机promise try / catch块之外,因此不会被捕获但是你的.catch()。