捕获Node js应用程序的所有uncaughtException [英] Catch all uncaughtException for Node js app

查看:92
本文介绍了捕获Node js应用程序的所有uncaughtException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:如何为我的节点应用程序处理所有未捕获的异常(操作/开发人员错误将导致所有服务中断).然后,只要发现错误,我都可以向我发送电子邮件警报.

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.

推荐答案

您可以使用流程'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应用程序的所有uncaughtException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆