首页 > 解决方案 > uncaughtExceptions 发送统计信息

问题描述

我的应用程序(在 NodeJS 中)正在收集用户统计信息。此过程的最后一步是使用 REST 发送这些收集的用户统计信息。因为这一步是最后一步,所以只要在申请过程中出现错误,就不会发送任何统计信息。我想将错误消息添加到统计信息中并发送。

在 NodeJS 中有一个事件UncaughtExeption,每当发生未捕获的错误时使用此事件发送用户统计信息是否安全?或者这是我的问题的错误方法?

标签: javascriptnode.jstypescriptstatistics

解决方案


在未捕获的异常之后发送您的统计信息是安全的,只要您之后退出该过程。恢复进程是危险的,因为应用程序处于未知状态。

我建议做如下的事情:

function sendStatistics() {
    // Send your stats via REST or whatever.
    console.log("sendStatistics: Sending statistics..")
}

process.on('uncaughtException', err => {
    // Should log exceptions here too.
    console.error(err, 'Uncaught Exception thrown');

    sendStatistics()

    // We must exit since the process is in an unknown state.
    process.exit(1);
});

uncaughtException上的 Node.js 文档解释了很多,包括如何正确使用事件。

具体来说:

'uncaughtException' 的正确用法是在关闭进程之前同步清理分配的资源(例如文件描述符、句柄等)。在“uncaughtException”之后恢复正常操作是不安全的。

我认为您可以将发送统计信息作为清理的一部分,因为这是一项至关重要的任务。


推荐阅读