Express-Mongoose请求-响应周期/使用exp处理错误

时间:2019-03-16 17:00:45

标签: node.js express error-handling

我的印象是res.send()结束了请求-响应周期,但是在else块中没有src = {i: i ** 3 for i in range(1000000)} # Taking items 1 by 1 (~0.0059s) dst = {} while len(dst) < 20000: item = src.popitem() dst[item[0]] = item[1] 的情况下,调用了return,它将响应对象传递给错误处理中间件,产生next(ex)

我的理解力在哪里?如果这很重要,我正在使用Error: Can't set headers after they are sent.来捕获错误。

express-async-errors

1 个答案:

答案 0 :(得分:1)

在您的问题中,您自己提到了next()函数将响应对象传递给错误处理中间件,因此即使您不希望将下一个中间件也成功执行,也将执行下一个中间件,但随后将调用next()函数。

您正在做什么(在else块中不返回):

发送allstaff对象并因此尝试结束请求响应周期,但随后调用next()从而调用下一个试图弄乱本来应该是成功的请求响应周期的中间件。

router.get('/', async (req, res, next) => {
  // get all staff sorted by name
  const allStaff = await Staff.find().sort('name');
  if (!allStaff) {
    res.status(404).send('No staff');
  } else {
   res.status(200).send(allStaff);   //send the response..expect the req-res cycle to end
  }
  next(ex);     //then call next which might try to hamper the outgoing response
});

您应该怎么做:

如果您发送响应,那么它绝不会遇到其他试图再次发送响应的语句,我个人更喜欢以下代码:

router.get('/', (req, res, next) => {
    // get all staff sorted by name
    Staff.find().sort('name').exec(function (err, docs) {     //this callback function will handle results
        if (err) {
            next();                                          //if there is an error..then the next middleware will end the req response cycle
        } else {                                             
            if (docs.length == 0) {
                res.status(404).send('No staff');           //send response,the req- res cycle ends,never disturbed again...story finished
            } else {
                res.status(200).send(docs);             //send response,the req- res cycle ends,never disturbed again.....story finished
            }
        }
    });


});