首页 > 解决方案 > 触发错误处理时,应用程序崩溃

问题描述

我有一条路线。

router.post('/add', async (req, res) => {
    ...
    await timeIntervalCheck(req, res);
    ...
    return res.status(200).json({
        message: 'Product added'
    });
}):

在其中,我调用函数timeIntervalCheck

这是函数本身:

function timeIntervalCheck(req, res) {
    let end_date = req.body.end_date;
    let starting_date = req.body.starting_date;
    let date = moment(end_date).diff(moment(starting_date), 'hours');
    if (date < 2 || date > 168) {
        return res.status(422).json({
            err: 'The product cannot be published for less than 2 hours and longer than 7 days'
        });
    }
}

如果产品的时间适合这个时期,一切都很好,但只要 periud 或多或少,就会出现错误Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我理解他的意思,因为当 periud 或多或少时,标题已经发送,我继续尝试再次发送它们。如何确保没有此类错误?如何发送更长时间的错误而不是发布产品已添加

标签: node.jsexpress

解决方案


我建议您检查结果timeIntervalCheck并发送正确的响应。(或者您可以检查res.headersent并停止两次发送响应,但我不喜欢这种方法)

router.post('/add', async (req, res) => {
  ...
  let checkResult = timeIntervalCheck(req); // please note that only async function requires await flag
  ...
  if (checkResult === true) {
    return res.status(200).json({
     message: 'Product added'
    });
  } else {
    return res.status(422).json({
      err: 'The product cannot be published for less than 2 hours and longer than 7 days'
    });
  }
}):

--

function timeIntervalCheck(req, res) {
  let end_date = req.body.end_date;
  let starting_date = req.body.starting_date;
  let date = moment(end_date).diff(moment(starting_date), 'hours');
  if (date < 2 || date > 168) {
    return false;
  } else {
    return true;
  }
}

}


推荐阅读