How to throw an error in Node

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To throw an error in Node.js, you instantiate a new Error object and throw it …

throw new Error('Something is wrong');

where ‘Something is wrong’ is your error message.  If the error is uncaught, the application will terminate at point, printing out a stack trace.

To catch exceptions, you can do …

process.on('uncaughtException', function(err) {
    console.error(err);
    process.exit(1);
});
throw new Error('Something is wrong');

Or you can bound it withing a try clause as in …

try {
	console.log("doing something");
	throw new Error('But something went wrong');

} catch ( e ) {
	console.log("We continue here despite our error: " + e);
}

And so that is how you throw an Error in Node and catching it.