gpt4 book ai didi

Node.js 表达 unhandledRejection removeListener

转载 作者:行者123 更新时间:2023-12-01 01:55:49 26 4
gpt4 key购买 nike

我的 Express 应用程序中有一些错误处理,用于异步/等待功能,即。尝试集中处理 Uncaught Error ,以适当的状态代码/消息进行响应。

我这样做:

const handleRejection = (res, reason) => {
const { code, message } = reason
console.trace()
logger.error(reason)
// use `res` to send response to client
}

app.use((req, res, next) => {
process.on('unhandledRejection', handleRejection.bind(this, res))
next()
})

process.on('SIGTERM', () => process.removeListener('unhandledRejection', handleRejection))

这可以很好地捕获/处理错误,但是,每次触发错误时,我的日志都会被填满。我不相信这个事件监听器, process.on('unhandledRejection') , 完全被正确删除...

有解决方案吗?

最佳答案

您似乎在每个请求上都附加了一个新的事件处理程序。

然后,在 SIGTERM 上,您尝试删除事件处理程序 handleRejection从未附加 - 你没有附加 handleRejection但是 handleRejection.bind(this, res)它返回一个不同的函数。

看起来你也可能通过将函数绑定(bind)到每个 res 来泄漏内存。每个请求的对象。

这是一种非常奇怪的错误处理方式。我什至不确定这确实是你想要做的。当您尝试退出服务器时,您是否想添加这么多事件处理程序(对服务器发出的每个请求一个),然后在 SIGTERM 上删除所有事件处理程序?

关于Node.js 表达 unhandledRejection removeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com