node.js - 触发错误处理时,应用程序崩溃
问题描述
我有一条路线。
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 或多或少时,标题已经发送,我继续尝试再次发送它们。如何确保没有此类错误?如何发送更长时间的错误而不是发布产品已添加
解决方案
我建议您检查结果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;
}
}
}
推荐阅读
- javascript - API 响应未定义
- regex - 我的正则表达式函数抛出非法转义异常
- reactjs - 如何将索引保存在 React.useState 中?
- javascript - 如何使用碳设计系统类显示多级下拉列表?
- php - How can i access Client data into custom Normalizer (Symfony 4)
- c# - 在反序列化期间填充数据网格时的性能问题
- django - 我想分别显示用户视频和其他视频。我没有从以下代码中获得输出,我的方法是否正确?
- javascript - 滚动到该 div 后如何使 div 切换到底部固定?
- python - 大型数据帧上的二维高斯过采样
- flutter - 如何在flutter中获取另一个文件的var的值?