Thursday, 20 April 2017

Exception Handling With Node In a JavaScript Promise

I'm having some difficulty correctly implementing an exception handler when a promise is involved with my node app.

The code below connects to a SQL Server database using Sequelize. I want to throw an exception to a client invoking a route for my API and the database is unavailable (taken offline, or is otherwise unreachable).

'use strict';
var Sequelize = require('sequelize');
var config = require('config');
var crypto = require('crypto-js');
module.exports = {
    connectDb: (function () {
        var sequelize, dbConfig;
        dbConfig = config.get('CONFIGFILE.dbConfig');

        function createInstance() {
            var sequelizeInstance, connectedAndAuthenticated, dbPassword;
            dbPassword = crypto.AES.decrypt(dbConfig.password, process.env.dbKey).toString(crypto.enc.Utf8);
            sequelizeInstance = new Sequelize(dbConfig.database, dbConfig.username, dbPassword, dbConfig.params);

            connectedAndAuthenticated = sequelizeInstance.authenticate();
            connectedAndAuthenticated.sequelize = sequelizeInstance;
            connectedAndAuthenticated.Sequelize = Sequelize;

            return connectedAndAuthenticated;
        }
        return {
            getInstance : function () {
                if (!sequelize) {
                    sequelize = createInstance()
                        .catch(function (err) {
                           console.log('Failed to connect to database ' + dbConfig.database + ' Reason: ' + err.message); 
                        });
                }
                return sequelize;
            }
        };
    }())
};

The issue comes up in the catch of the promise where I create my database instance - the line is logged and the API response is a 401 Unauthorized.

However, I realized that I am actually no longer returning an instance of Sequelize by doing this, so I changed it to a traditional try/catch block:

if (!sequelize) {
                    try {
                        sequelize = createInstance();
                    } catch (e) {
                        console.log('Failed to connect to database: ' + e.message);
                    }
                }

Which, in this "database down" condition, ends up tripping nodes unhandledRejection event and the request just hangs.

What is the correct way to do this?



via Elliot Rodriguez

No comments:

Post a Comment