Node.js oracledb module -- TypeError: 无法读取未定义的属性'close'



我正在尝试使用Oracledb npm for Nodejs运行简单的SQL语句。这在过去一直有效,没有任何问题,但突然间,我在不同的环境中出现了这个错误。可能是因为别名?我不确定。

导致问题的线路的目标是在连接完成或失败后关闭连接。我直接在这里的Oracle文档中找到了逻辑:http://oracle.github.io/node-oracledb/doc/api.html#connectionclose

真的很感谢任何帮助!

const oracledb = require('oracledb');
const async = require('async');
const {getAwsSecret} = require('./awssecret');
var alias = "";
async function initialize() {
// Set Oracle Pool Settings
let hrPool = {
poolMin: 10,
poolMax: 10,
poolIncrement: 0
}
var secret = await getAwsSecret('MAIN');
const secretJSON = JSON.parse(secret);
hrPool.user = secretJSON[process.env.CURENV + 'username'];
hrPool.password = secretJSON[process.env.CURENV + 'password'];
hrPool.connectString = secretJSON[process.env.CURENV + 'host'] + '/' + secretJSON[process.env.CURENV + 'dbname'];
hrPool.poolAlias = secretJSON.alias;
alias = secretJSON.alias;
try { 
await oracledb.createPool(hrPool);
} catch (err) {
console.log(err);
}
}
module.exports.initialize = initialize;
async function close() {
await oracledb.getPool().close();
}
module.exports.close = close;
async function simpleExecute(statement, binds = [],clientdetails = [], opts = {}) {
let conn;
opts.outFormat = oracledb.OBJECT;
opts.autoCommit = true;
try {
// Get Connection
conn = await oracledb.getConnection(alias);
// Run Query
const result = await conn.execute(statement, binds, opts);
///////////// POST EXECUTION HANDLING /////////////
if (conn) { // conn assignment worked, need to close
try {
// Close Connection
await conn.close();
// Return Result
return result;
} catch (err) {
console.log(err);
}
}
///////////// POST EXECUTION HANDLING /////////////
} catch (err) {
await conn.close();
} 
}
module.exports.simpleExecute = simpleExecute;

错误:

TypeError: Cannot read property 'close' of undefined 2021-04-23T14:36:51.269-04:00  at 
Object.simpleExecute (/usr/src/app/services/database.js:59:18)

如果获取连接时出错,catch块会在没有有效conn的情况下调用conn.close()。这给出了您看到的错误。这可能不是唯一的原因,但整理代码会有所帮助。

您的conn.close()在一个finally()块中可能只有一次。看看example.js之类的例子,例如:

let connection;
try {
connection = await oracledb.getConnection(dbConfig);
result = await connection.execute(sql, binds, options);
console.dir(result, { depth: null });
} catch (err) {
console.error(err);
} finally {
if (connection) {
try {
await connection.close();
} catch (err) {
console.error(err);
}
}
}

其他一些提示:

  • 如果您的代码要连续执行几个语句,那么不要对每个语句执行getConnection()/close()。这会影响池的可伸缩性,因为共享池资源上存在一些锁存,并且会为整个步骤添加额外的代码
  • 避免总是承诺。如果不必要,这可能会破坏事务一致性并增加开销
  • pool.close()调用中使用显式drainTime以确保它已关闭,请参阅webapp.js

相关内容

最新更新