我可以在try Catch块上使用res.end()吗?

smdncfj3  于 2022-10-12  发布在  Node.js
关注(0)|答案(2)|浏览(122)

我使用的是节点路由,我使用的是trycatch块,但Node.js没有。当代码有错误时,它会转到Catch,它会失败。

try {
 ... 
 res.send({ message: 'All good nothing wrong with the code above' })
} catch {
 res.status(500).send({ message: 'There is an error I want to send to the front end' })
}

Node显然对此不满意,我知道我无法发送res.send()twice,但它位于trycatch块上。如果出现故障,我如何向前端发送错误消息?

节点在CATCH块上抱怨:

'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'

更新

我修复了这个问题,方法是将错误对象WITH发送到CATCH块,并且不对除一次以外的任何条件使用TRY CATCH上的res.send()

3qpi33ja

3qpi33ja1#

当您想要发送一些东西而不做其他任何事情时,终止函数的执行流总是很好的。

res.send('All ok');
console.log('Response sent');
return;

or

return res.send('All ok');

try {
   throw Error('Oops')
   return res.send('OK')
} catch(error) {
   return res.send('Not OK: ' + error.message)
}
ndasle7k

ndasle7k2#

您不能使用两次res.send,因此请添加return

try {
 ... 
} catch {
   res.status(500).send({ message: 'There is an error I want to send to the front end' })
   return;
}
res.send({ message: 'All good nothing wrong with the code above' })

相关问题