🟢 Node - Error Handling
Updated at 2015-07-25 16:41
Pass Error objects, not strings.
Always check for errors when writing callbacks. It is standard practice to use callbacks that have error as the first parameter. That error parameter is either Error
object or null
if no error happened.
// bad
function writeCsvFile(target, data, callback) {
convertToCsv(data, function(err, csv) {
writeFile(target, csv, callback);
});
}
// good
function writeCsvFile(target, data, callback) {
convertToCsv(data, function(err, csv) {
if (err) {
return callback(err);
}
writeFile(target, csv, callback);
});
}
Don't throw exceptions inside asynchronous code. They cannot be caught. Pass the error into the callback. Passing null as error means everything went ok.
// bad
function getRecord(id, callback) {
http.get('http://foo/' + id, function(err, doc) {
if (err) {
return callback(err);
}
if (doc.deleted) {
// this will not get caught by the function calling getRecord
throw new Error('Record has been deleted');
}
return callback(null, doc);
});
}
// good
function getRecord(id, callback) {
http.get('http://foo/' + id, function(err, doc) {
if (err) {
return callback(err);
}
if (doc.deleted) {
return callback(new Error('Record has been deleted'));
}
return callback(null, doc);
});
}
Throw exceptions on errors that should crash the server. Returning an Error object is standard pattern used with Node.js.
Restart on uncaught exception. Server restart on exception is standard pattern in Node applications. Log the error, restart the application and keep on going.