Questions And Answers

More Tutorials

NodeJS Exception handling

Handling Exception In Node.Js

Node.js has 3 basic ways to handle exceptions/errors:

1. try-catch block
2. error as the first argument to a callback
3. emit an error event using eventEmitter

try-catch is used to catch the exceptions thrown from the synchronous code execution. If the caller (or the caller's caller, ...) used try/catch, then they can catch the error. If none of the callers had try-catch than the program crashes.

If using try-catch on an async operation and exception was thrown from callback of async method than it will not get caught by try-catch. To catch an exception from async operation callback, it is preferred to use promises.
Example to understand it better

// ** Example - 1 **
function doSomeSynchronousOperation(req, res) {
 if(req.body.username === ''){
 throw new Error('User Name cannot be empty');
 return true;
// calling the method above
try {
 // synchronous code
 doSomeSynchronousOperation(req, res)
catch(e) {
 //exception handled here
// ** Example - 2 **
function doSomeAsynchronousOperation(req, res, cb) {
 // imitating async operation
 return setTimeout(function(){
 cb(null, []);
try {
 // asynchronous code
 doSomeAsynchronousOperation(req, res, function(err, rs){
 throw new Error("async operation exception");
} catch(e) {
 // Exception will not get handled here
// The exception is unhandled and hence will cause application to break

callbacks are mostly used in Node.js as callback delivers an event asynchronously. The user passes you a function (the callback), and you invoke it sometime later when the asynchronous operation completes.

The usual pattern is that the callback is invoked as a callback(err, result), where only one of err and result is non-null, depending on whether the operation succeeded or failed.

function doSomeAsynchronousOperation(req, res, callback) {
 return callback(new Error('User Name cannot be empty'));
 }, 1000);
 return true;
doSomeAsynchronousOperation(req, res, function(err, result) {
 if (err) {
 //exception handled here

 //do some stuff with valid data

emit For more complicated cases, instead of using a callback, the function itself can return an EventEmitter object, and the caller would be expected to listen for error events on the emitter.

const EventEmitter = require('events');
function doSomeAsynchronousOperation(req, res) {
 let myEvent = new EventEmitter();
 // runs asynchronously
 myEvent.emit('error', new Error('User Name cannot be empty'));
 }, 1000);
 return myEvent;
// Invoke the function
let event = doSomeAsynchronousOperation(req, res);
event.on('error', function(err) {
event.on('done', function(result) {
 console.log(result); // true


In this page (written and validated by ) you learned about NodeJS Exception handling . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS Keep a node application constantly running.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.