How to handle errors in Node.js?

Error Handling is important in any of the language. If you don’t handle errors, then your program may crash or go to inconsistent state.

In Node, we have Error-first callback as the  standard protocol for callbacks. This is very simple convention with only one rule, the first argument for the callback function should be the error object.

That is there are following two scenarios:

1. Your Error argument is null, then your program is without error.

2.  Your Error argument is not null, then you need to handle error.

Example of Error-first callback:

fs.readFile(‘/foo.txt’, function(err, data) {
// …
});

Here, readFile has two parameters error and file data.

To handle err, you just need to put a check for getting value of err.

If( err ){
console.log(err);
}else{
console.log(“working fine”);
}

EventEmitter errors:

When working with event emitters , you should be careful. If there’s an unhandled error event it will crash our application.

Example of eventEmitter:

var EventEmitter = require(‘events’).EventEmitter;
var emitter = new EventEmitter();
emitter.emit(‘error’, new Error(‘something bad happened’));

You can handle event emitter errors as shown below:

emitter.on(‘error’, function(err) { console.error(‘something went wrong with the ee:’ + err.message); });

Propagating more descriptive errors with the verror module:

There are some situations where we don’t handle errors ourselves. We just delegate it to callback.In above way of handling errors, we don’t get exact stack trace.

In real world applications, there will probably be a function that calls another function that calls the original function. So, to know from where exactly error came.

For this Node has verror module, which we have to integrate with the application.With verror, we can wrap our errors to provide more descriptive messages.

We will have to require the module at the beginning of the file and then wrap the error when invoking the callback:

var verror = require(‘verror’);
function readFiles(files, callback) { …
return callback(new VError(err, ‘failed to read file %s’, filePath));

}

 


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>