node.js - 使用 promises 在 Node.js + Express 中处理错误

标签 node.js express error-handling mongoose promise

使用 Node.js + Express (4) + Mongoose(使用 promises 而不是回调),我不知道如何整理我的错误处理。

我得到的(相当简化的)是:

app.get('/xxx/:id', function(request, response) {
    Xxx.findById(request.params.id).exec()
        .then(function(xxx) {
            if (xxx == null) throw Error('Xxx '+request.params.id+' not found');
            response.send('Found xxx '+request.params.id);
        })
        .then(null, function(error) { // promise rejected
            switch (error.name) {
                case 'Error':
                    response.status(404).send(error.message); // xxx not found
                    break;
                case 'CastError':
                    response.status(404).send('Invalid id '+request.params.id);
                    break;
                default:
                    response.status(500).send(error.message);
                    break;
            }
        });
});

在这里,在“promise rejected”部分的开关中,Error 是我为未找到的潜在有效 ID 而抛出的错误,CastErrorCast to ObjectId failed 由 Mongoose 因无效 ID 抛出,并且 500 错误可以通过将 throw Error() 错误输入为 throw Err() 来触发(导致 ReferenceError: Err is not defined)。

但是像这样,我的每条路线都有这个笨拙的大开关来处理不同的错误。

如何集中处理错误?能否以某种方式将开关隐藏到某些中间件中?

(我确实希望我可以在“promise rejected” block 中使用 throw error; 重新抛出,但我没能成功)。

最佳答案

我会创建中间件来处理错误。使用 next() 处理 404。和 next(err) 用于其他错误。

app.get('/xxx/:id', function(req, res, next) {
  Xxx.findById(req.params.id).exec()
    .then(function(xxx) {
      if (xxx == null) return next(); // Not found
      return res.send('Found xxx '+request.params.id);
    })
    .then(null, function(err) {
      return next(err);
    });
});

404处理程序

app.use(function(req, res) {
  return res.send('404');
});

错误处理器

app.use(function(err, req, res) {
  switch (err.name) {
    case 'CastError':
      res.status(400); // Bad Request
      return res.send('400');
    default:
      res.status(500); // Internal server error
      return res.send('500');
  }
});

您可以通过发送像这样的 json 响应来改进这一点:

return res.json({
  status: 'OK',
  result: someResult
});

return res.json({
  status: 'error',
  message: err
});

关于node.js - 使用 promises 在 Node.js + Express 中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470535/

相关文章:

javascript - noob : node. js writeHead 停止我的代码

node.js - Mongoose Schema 数字字段的长度是准确的

mysql - 查询时如何使用sequelize迁移模型?

Node.js:使用domain.dispose()

node.js - 以 Express 方式发送对象会导致空对象

bash - Bash 中的错误处理

javascript - Passport JS -> require(...) 不是函数

javascript - 在socket.io中搜索对手

javascript - 为什么最后一个元素总是在悬停时触发?

node.js - 有关为node.js安装angular cli的问题