首页 > 解决方案 > 如何抛出我自己的不显示调用堆栈的错误?

问题描述

我有一个带有 2 个 JavaScript 文件的简单应用程序。如何抛出我自己的安全错误(来自 service.js 的 insertorupdate),这样调用堆栈就不会显示给用户?

控制台.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);
    }

})();

合同服务.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);
            });
    });
}

标签: node.jssequelize.js

解决方案


为了避免一般显示调用堆栈,只需执行以下操作:

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

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

推荐阅读