Node.js Best Practice Exception Handling

后端 未结 10 1465
遥遥无期
遥遥无期 2020-11-22 04:19

I just started trying out node.js a few days ago. I\'ve realized that the Node is terminated whenever I have an unhandled exception in my program. This is different than the

10条回答
  •  别那么骄傲
    2020-11-22 05:03

    Catching errors has been very well discussed here, but it's worth remembering to log the errors out somewhere so you can view them and fix stuff up.

    ​Bunyan is a popular logging framework for NodeJS - it supporst writing out to a bunch of different output places which makes it useful for local debugging, as long as you avoid console.log. ​ In your domain's error handler you could spit the error out to a log file.

    var log = bunyan.createLogger({
      name: 'myapp',
      streams: [
        {
          level: 'error',
          path: '/var/tmp/myapp-error.log'  // log ERROR to this file
        }
      ]
    });
    

    This can get time consuming if you have lots of errors and/or servers to check, so it could be worth looking into a tool like Raygun (disclaimer, I work at Raygun) to group errors together - or use them both together. ​ If you decided to use Raygun as a tool, it's pretty easy to setup too

    var raygunClient = new raygun.Client().init({ apiKey: 'your API key' });
    raygunClient.send(theError);
    

    ​ Crossed with using a tool like PM2 or forever, your app should be able to crash, log out what happened and reboot without any major issues.

提交回复
热议问题