Sony Arouje

a programmer's log

Archive for November 7th, 2014

Node js error handling using modules inherited from EventEmitter

leave a comment »

In node js most of the operations are asynchronous and normal try-catch will not work. In case of any error and we didn’t handle it properly, our node process will crash. In this post I will explain how to handle errors properly using EventEmitter.

In this e.g. we are going to read some data from a SQLite db, I use dblite as my node module to deal with SQLite db. For this e.g. I created a UserRepository module and inherited from EventEmitter


var dblite = require('dblite');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var UserRepository = function () {
    var self = this;

    self.getUser = function (userid, callback) {
        db.query('select * from USER where USER_ID=:id', [], { id: userId },
        function (err, rows) {
            if (err)


    var publishErr = function (err) {
        self.emit('error', err);

util.inherits(UserRepository, EventEmitter);
module.exports = UserRepository;


Using util.inherits, we inherits the UserRepository module from EventEmitter. Later we export that module to use in other node modules. The publishErr() function will emit an ‘error’ event in case of any error and calling module can subscribe to that event and handle the error.

Let’s use the above module in another node module. Say an express rest api.


var express = require('express');
var bodyParser = require('body-parser')

var UserRepository = require('./UserRepository');
var userRepo = new UserRepository();

var app = express();

userRepo.on('error', function (err) {

app.get('/users/;id', function (req, res) {
    userRepo.getUser(, function (record) { 



Let’s go through the lines in bold.

Here we are creating the instance of UserRepository module.

var UserRepository = require('./UserRepository');
var userRepo = new UserRepository();

The calling module should subscribe for the error event, that’s what we are doing here. I am just writing the error to the console. You can do whatever you want with that err object.

userRepo.on('error', function (err) {


This way we can ensure that our errors are handled properly in an elegant way.

Node js has an uncaughtException event and use it as a last resort.

process.on('uncaughtException', function (err) {

Written by Sony Arouje

November 7, 2014 at 5:47 pm

Posted in .NET

%d bloggers like this: