Node.js Express unhandledRejection removeListener

我在快速应用程序中有一些error handling,用于asynchronous/等待function,即。 试图集中处理未被捕获的错误,以适当的状态代码/消息进行响应。

我正在这样做:

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') ,正在被正确删除…

有这个解决scheme吗?

看起来你是在每个请求上附加一个新的事件处理程序。

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

它看起来像你也可能泄漏内存通过绑定函数的每个res对象为每个请求。

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

这是我的Express中间件的解决scheme,将未处理的拒绝传递给主错误中间件

  // Handle unhandledRejection and pass error to next middleware app.use(function (req, res, next) { function unhandledRejection(reason, p) { console.error('Possibly Unhandled Rejection at: Promise ', p, " reason: ", reason); next(reason); } process.on('unhandledRejection', unhandledRejection); // Manage to get information from the response too, just like Connect.logger does: var end = res.end; res.end = function (chunk, encoding) { // Prevent MaxListener on process.events process.removeListener('unhandledRejection', unhandledRejection); res.end = end; res.end(chunk, encoding); }; next(); });