Error handling in Node.js

-

Introduction

Due to the asynchronous, event based system of Node.js, the approach to error handling is slightly different when compared to many other back-end languages. 

When dealing with JavaScript you often deal with multiple nested callbacks therefore leaving room for uncaught errors and thus your Node.js application falls over. 

 

Catching Non-Asynchronous Errors

try {
  if(freelanceDeveloper == ‘Jordizle’) {
    // do something 
  } else {
    var error = new Error(‘error..);
    throw error;
  }
} catch (error) {
    console.log(error); // handle the error 
}

The above code uses a try-catch statement to ensure that the error is handled safely. 

Catching Asynchronous Errors

The wrong way:

var collections = { };
function count(collection, callback) {
  collections[collection].find({ }).count(function (error, number) {
    throw new Error(‘error…’);
    callback(number);
  });
}
// will cause uncaught error
try {
  count(‘users’, function(result){
    console.log(result);
  });
} catch (error) {
    console.log(error); // handle the error 
}

The right way:

var collections = { };
function count(collection, callback) {
  collections[collection].find({ }).count(function (error, number) {
    if(error) {
      callback(error);
    } else {
      callback(number);
    }
  });
}
// will be caught properly
try {
  count(‘users’, function(result){
    if(value instanceof Error) {
      var error = result;
      throw error;
    } else {
      console.log(result);
    }
  });
} catch (error) {
  console.log(error); // handle the error 
}

Tips and Tricks

Forever is a script that detects when your server falls over and automatically restarts it therefore keeping your server up and running. 

Your comments.