Search code examples
node.jsnginxpm2

How can I see the error when Node Js has stopped?


I have a NodeJs server with nginx. It runs on ubuntu server. it shows "502" from time to time. I am running it via pm2. The real issue is now: when I log in and look at pm2 it doesn't show "error". When I run "restart", "502" goes away and starts working normally. Question:
1.) Can I send an e-mail automatically when the server stops?
2.) can I write every event to a file in the application? (Can I see the error by looking at the last event?) I am using MongoDB.
3.) How can I catch the error?


Solution

  • There are multiple ways to do it. You are not getting properly log and stopped/restarted the application that means your application needs code quality improvement and error handling properly.

    You may use uncaughtException and unhandledRejection events to send email and log into a file

    process
      .on('unhandledRejection', (reason, p) => {
        //'Unhandled Rejection at Promise'
        // send email or write into file
      })
      .on('uncaughtException', err => {
        //'Uncaught Exception thrown'
        // send email or write into file
        process.exit(1);
      });
    

    Apart from the above, you may use a third-party monitoring tool even pm2 also provides