捕获 Node js 应用程序的所有未捕获异常 [英] Catch all uncaughtException for Node js app
问题描述
我有一个问题:如何处理我的节点应用程序的所有未捕获异常(操作/开发人员错误将导致所有服务停止).然后我可以在发现错误时向我发送电子邮件警报.
I have a question: how do I can handle all uncaught Exception (operations/developer error will take all service down) for my node app. Then I can send an email alert to me whenever catch an error.
推荐答案
您可以使用 process 'uncaughtException
' 和 'unhandledRejection
' 事件.
You can use process 'uncaughtException
' and 'unhandledRejection
' events.
还要记住在'uncaughtException
'之后恢复正常操作是不安全的,因为系统损坏:
Also remember that it is not safe to resume normal operation after 'uncaughtException
', because the system becomes corrupted:
'uncaughtException
' 的正确用法是执行同步清理分配的资源(例如文件描述符、句柄等)在关闭进程之前.
The correct use of '
uncaughtException
' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process.
示例:
process
.on('unhandledRejection', (reason, p) => {
console.error(reason, 'Unhandled Rejection at Promise', p);
})
.on('uncaughtException', err => {
console.error(err, 'Uncaught Exception thrown');
process.exit(1);
});
这篇关于捕获 Node js 应用程序的所有未捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!