Tuesday, 10 April 2012

Exception handling in Node

A common problem when writing Node.js programs is in ensuring all exceptions are handled. Node.js will helpfully die when exceptions are not caught and handled, which forces you, the author, to ensure robustness in your Node.js applications.  Node emits an uncaughtException event when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur.
process.on('uncaughtException', function (ex) {
    console.log('Unhandled exception caught: ' + ex);

If you are writing asynchronous code, you can follow the below given pattern to throw and handle exceptions in the code. In this pattern the first argument of the callback is err, if an error happens it is the error, if it doesn't it is null.
var divideAsync = function (arg1, arg2, callback) {
    if (arg2 == 0) return callback(new Error('division by 0 is not possible'));
    return callback(null, arg1 / arg2);

divideAsync(9, 0, function (ex, result) {
    if (ex) {
        console.log('Error in division ' + ex);
    console.log('result ' + result);

You can also use the traditional try {} catch (err) {} to catch exceptions as given below
console.log('Starting directory: ' + process.cwd());
try {
    console.log('New directory: ' + process.cwd());
catch (err) {
    console.log('chdir: ' + err);

For synchronous code, if an error happens you can return an instance of Error object and later check the result for this object as given below.
var divide = function (arg1, arg2) {
    if (arg2 == 0) return new Error('division by 0 is not possible');
    return arg1 / arg2;

var x = divide(5, 0);
if (x instanceof Error) {
    console.log('Exception logged');

No comments:

Post a Comment