Catch all uncaughtException for Node js app

后端 未结 3 1452
长发绾君心
长发绾君心 2020-12-03 06:49

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 w

3条回答
  •  误落风尘
    2020-12-03 07:27

    You can use process 'uncaughtException' and 'unhandledRejection' events.

    Also remember that it is not safe to resume normal operation after 'uncaughtException', because the system becomes corrupted:

    The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process.

    Example:

    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);
      });
    

提交回复
热议问题