Sony Arouje

a programmer's log

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

UserRepository.js

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)
                publishErr(err); 

            callback(rows);
        });
    };

    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.

restApi.js

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

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

var app = express();
app.use(bodyParser.json());
app.listen(8080);

userRepo.on('error', function (err) {
    console.log(err);
});

app.get('/users/;id', function (req, res) {
    userRepo.getUser(req.params.id, function (record) { 
        res.send(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) {
    console.log(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) {
    console.log(err);
})
Advertisements

Written by Sony Arouje

November 7, 2014 at 5:47 pm

Posted in .NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: