【发布时间】:2016-10-10 11:55:51
【问题描述】:
我对 promises 不熟悉,现在正在玩弄它们。我已经创建了这个基本应用程序:
var Promise = require("bluebird");
var express = require('express');
var bcrypt = require('bcrypt-nodejs');
var app = express();
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
getStuffFromDb('my_password')
.then((hash) => {
console.log('hash = ' + hash);
return hash;
})
.then((hash) => {
res.send(hash);
})
.catch(function(error) {
errorHandler(error, res)
});
});
function getStuffFromDb(password) {
return new Promise(function(resolve, reject) {
//This should fail because it is missing a parameter, a number to specify how many loops
bcrypt.genSalt(function(error, result) {
if (error) {
return reject(Error("It broke 1"));
}
//This should cause an error as result_which_does_not_exist is not defined, and the call to the function should be bcrypt.hash(password, result_which_does_not_exist ...) so it is missing a parameter
bcrypt.hash(result_which_does_not_exist, null, function(err, hash) {
if (err) {
return reject(Error("It broke 2"));
} else {
return resolve(hash);
}
});
});
});
}
function errorHandler(error, res) {
res.send(error.message);
}
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
因此,由于缺少参数,因此应用程序应该在生成盐时失败。相反,它在密码散列时失败,因为缺少一个参数并且我传入了一个不存在的变量。这导致我的服务器崩溃并出现以下错误:
bcrypt.hash(result_which_does_not_exist, null, function(err, hash) { ReferenceError: result_which_does_not_exist is not defined.
所以应用程序正在崩溃,但我希望处理此错误,我不希望它使我的服务器崩溃。我怎样才能做到这一点?我对 promises 很陌生(阅读它们大约需要 1 小时),但根据我的理解,catch 应该抓住了这个?
【问题讨论】:
-
@vp_arth 抱歉,但我看不出你发布的这个重复的答案是如何在这里应用的?接受的答案关于如何捕获错误的部分推荐了现在已弃用的域。我正在使用 Promise,而 Promise 并没有按照我期望的方式捕获结果。
-
@vp_arth 我不认为这个问题应该被标记为重复?副本指定了如何在 nodejs 中捕获错误,我的问题是关于为什么这个承诺没有被捕获。您能否解释一下它们是如何重复的,因为我认为这个问题之间没有相关性?
标签: node.js error-handling promise bluebird