Error Handling

Depending on the type of code (sync, promise, async callback, async await, etc) Node allows us to handle our errors how we see fit.

Process exiting

When an exception is thrown in Node.js, the current process will exit with a code of 1. This effectively errors out and stops your programming completely. You can manually do this with:

process.exit(1)

Although you shouldn't. This is low level and offers no chance to catch or handle an exception to decide on what to do. Imagine your entire API shutting down and restarting just because a user sent a malformed payload that resulted in the DB throwing an exception.

Async Errors

When dealing with callbacks that are used for async operations, the standard pattern is:

fs.readFile(filePath, (error, result) => {
  if (error) {
    // do something
  } else {
    // yaaay
  }
})

Callbacks accept the (error, result) argument signature where error could be null if there is no error.

For promises, you can continue to use the .catch() pattern. Nothing new to see here.

For async / await you should use try / catch.

try {
  const result = await asyncAction()
} catch (e) {
  // handle error
}

Sync Errors

For sync errors, try / catch works just fine, just like with async await.

try {
  const result = syncAction()
} catch (e) {
  // handle error
}

Catch All

Finally, if you just can't catch those pesky errors for any reason. Maybe some lib is throwing them and you can't catch them. You can use:

process.on('uncaughtException', cb)