在我的 promise 堆栈深处,我做出了这个调用:
function isNameAvailable(name) {
return registry.getName(name)
.then(function(result) {
return result ? false : true;
});
}
不幸的是,这是一个编程错误,注册表未定义。我的 Node.js 应用程序没有打印任何错误消息。有什么想法吗?我正在使用 bluebird Promise 库。
编辑
这是调用代码。我刚刚添加了捕获,但它没有捕获任何东西。
function _checkAvailability(name) {
return isNameAvailable(name)
.then(function(isAvailabile) {
if (isAvailabile) {
return true;
}
else {
throw new NameNotAvailable('Name "' + name + '" is not available');
}
})
.catch(function(error) {
console.log('isNameAvailable threw', error);
throw error;
})
}
堆栈最终应该回滚到由express.js 作为 HTTP 请求的结果调用的函数。这是我捕获所有错误并打印堆栈跟踪的地方(但显然它没有打印任何内容):
function createUser(req, res) {
userService.createUser(req.body)
.then(function(user) {
res.status(201).send(user);
})
.catch(function(error) {
log.trace(error);
res.status(500).send({'message': error.toString()});
});
}
最佳答案
进行编辑以反射(reflect)您的更新:
Naresh 是对的,如果抛出异常,您需要从 is name available 返回一个被拒绝的 promise 。你可以试试
function isNameAvailable(name) {
try {
return registry.getName(name)
.then(function(result) {
return result ? false : true;
});
} catch(e){
return Promise.reject(e)
}
}
请参阅这篇文章,了解深陷 promise 中的错误。
http://www.mattgreer.org/articles/promises-in-wicked-detail/#promises-can-swallow-errors-
关于javascript - 为什么 node.js/bluebird 会出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583599/