New Toronto Group
 - New Toronto Group

Building Robust Node.js Applications - Part 1: Errors

| Posted on November 25th, 2014 by Hasan Ahmad


There are plenty of resources available online that will help you get started on building node.js apps and get them up and running. The tricky part comes when you need to deal with making your node.js applications more robust and reliable, particularly by handling errors.

Node.js applications mostly depend on using asynchronous APIs. While there are always parts of an application that will run synchronously, it is important to think about how you mix the use of synchronous and asynchronous errors.

There are three common ways to handle errors in your node:

  • The throw keyword
  • Passing errors through a callback
  • Using error EventEmitters

Using the throw keyword allows you to synchronously throw an error, which turns that error into a JavaScript exception. Exceptions need to be handled in the usual try/catch way, by the calling function.

For example:

function sum (a, b) {
  if (typeof a === 'undefined') || (typeof b === 'undefined') {
    throw new Error('a or b is undefined');
  }
  // compute the sum of a and b and return it
  ...
}

I suggest using this type of error for input validation (missing arguments, or invalid arguments).

Callback errors and EventEmitter errors are asynchronous ways to pass errors back to a client. This is extremely common in node modules where you need to handle routine error scenarios such as file existence or network connection problems.

The fs core node module for interacting with the file system has many examples:

fs.readFile('/temp/configFile', 'r', function (err, fd) {
  if (err) {
    //handle error
  }
  //... do something with file descriptor
});

Callback errors are well suited for scenarios where you may have to handle multiple errors or different types of errors for a specific function call. In functions where many things can go wrong, it makes a lot of sense to use callback errors to handle them as they come up in an asynchronous manner.

It is generally not advised to use both synchronous and asynchronous errors for a specific situation. Robust node.js applications often handle each error appropriately and individually.

Error handling is just one part of building robust node.js apps, keep an eye out for future posts on this topic from me.

Posted in Node.js  | Comments (0)

Comments (0)


Add a Comment





To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey

Allowed tags: <b><i><br>Add a new comment: