Rod
Rod

Reputation: 15475

How do I throw my own error that doesn't show the call stack?

I have a simple app with 2 JavaScript files. How do I throw my own safe error (from the insertorupdate of service.js) so the call stack isn't revealed to user?

console.js

const contracts = require('./contractService');

(async () => {

    let contractToUpdate = {
        idContract: 102,
        AccountNo_Lender: 'Back to resolve'
    };

    try {
        var results2 = await contracts.update(contractToUpdate);
        console.log(results2);
    } catch (error) {
        console.log(error);
    }

})();

contractService.js

require('dotenv/config');
const Sequelize = require('sequelize');

const sequelize = new Sequelize(process.env.DATABASE, process.env.USER, process.env.PASSWORD, {
    host: process.env.HOST,
    dialect: 'mysql',
    operatorsAliases: false,
    define: {
        timestamps: false,
        freezeTableName: true
    },

    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }

});

sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

/**
 * Model for the contract entity.
 */
const Contract = sequelize.define('Contract', {
    idContract: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    AccountNo_Lender: {
        type: Sequelize.STRING,
        allowNull: false
    }
});

exports.update = function (contract) {
    return new Promise(function (resolve, reject) {
        Contract.insertOrUpdate(contract)    <====== Right here don't throw call stack
            .then(c => {
                resolve(c);
            });
    });
}

Upvotes: 2

Views: 59

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

To avoid showing the callstack in general, just do:

function someFunction()
{
    throw new Error("Something bad happened");
}

try
{
   someFunction();
}
catch (err)
{
    console.error("Error message: " + err.message);
}

Upvotes: 2

Related Questions