我怎样才能兑现承诺呢?

时间:2020-05-22 17:40:37

标签: javascript node.js express

我有以下js表达代码:

app.get('/lists2', (req, res) => {
  mongo.getDB()
    .then(db => db.collection('dogs'))
    .then(collection => collection.find().toArray())
    .then(array => res.json(success(array)))
    // How can I throw in the middle of a promise to trigger express's middleware?
    .catch(error => {
      throw {message: "database error"};
    });
});

app.use(function (err, req, res, next) {
  const message = err.message || 'Encountered a server error';
  const status = err.status || 500;
  res.status(status).json({status, message});
})

我已经编写了一个中间件错误处理程序,因此我可以使用throw触发API错误响应,问题是我不能扔到then里面,因为它在异步代码中,是否有任何方法可以避开这个?还是我的错误处理模式不正确?

1 个答案:

答案 0 :(得分:1)

您应使用next(参见doc):

app.get('/lists2', (req, res, next) => {
  mongo.getDB()
    .then(db => db.collection('dogs'))
    .then(collection => collection.find().toArray())
    .then(array => res.json(success(array)))
    // How can I throw in the middle of a promise to trigger express's middleware?
    .catch(error => {
      next(new Error("database error"));
    });
});

app.use(function (err, req, res, next) {
  const message = err.message || 'Encountered a server error';
  const status = err.status || 500;
  res.status(status).json({status, message});
})
相关问题