Error Handling in Node.js

Checklist for Robust Error Handling #

Here's a checklist to ensure that errors don't go undetected in your Node.js application:

Notify yourself of uncaught exceptions #

The following code snippet will help you in detecting uncaught exceptions in productions:

var nodemailer = require('nodemailer')
var transport = nodemailer.createTransport('SMTP', { // [1]
  service: "Gmail",
  auth: {
    user: "[email protected]",
    pass: "userpass"
  }
})

if (process.env.NODE_ENV === 'production') { // [2]
  process.on('uncaughtException', function (er) {
    console.error(er.stack) // [3]
    transport.sendMail({
      from: '[email protected]',
      to: '[email protected]',
      subject: er.message,
      text: er.stack // [4]
    }, function (er) {
       if (er) console.error(er)
       process.exit(1) // [5]
    })
  })
}