Nodejs 并不总是显示错误

Nodejs not always showing errors

我开始学习js和nodejs了。我遇到了一个问题,我花了很长时间才解决。

我正在使用 bcrypt 库,但我在 require statemant 上打错了字:

const bcrpyt = require('bcryptjs');

然后在我使用的预保存模式中:

bcrypt.hash(user.password, 10, (err, hash) => {
    user.password = hash;
    next();
});

所以 bcryptundefined

在我的路线上我有:

user.save()
    .then(/*some action*/)
    .catch(e => res.status(400).send(e));

所以在发出请求后,我得到了状态 400 但 e 是空对象 {}

知道为什么没有 "calling hash on undefined" 之类的错误吗?

您只能向客户端发送消息:

res.status(400).send(e.message)

我不知道你使用的是 express.js 还是普通的 node.js 但如果你想在客户端看到这些错误,你可以将整个服务器请求代码包装在一个 try catch 中像这样阻塞(使用 vanilla nodejs):

http.createServer(function(request, response) {
    try{
        response.writeContinue(undefinedVariable);
    }catch (error) {
        response.status(400).end(error.message);
    }
}).listen(port);