You need to enable JavaScript to run this app. 为何try catch无法捕获oracledb.createPool回调中抛出的未处理异常
优惠活动
大模型
产品
解决方案
定价
更多

为何try catch无法捕获oracledb.createPool回调中抛出的未处理异常

问题原因

  • 你同时混用了await异步等待和回调两种调用模式,回调函数内抛出的异常属于独立的异步执行上下文,和外层的try/catch不属于同一个调用栈,因此外层无法捕获回调内部抛出的错误。
  • oracledb.createPool方法本身支持两种调用方式:传入回调时走回调逻辑,不传回调时会返回Promise对象,可直接用await等待执行结果。

解决方法

直接移除回调参数,完全使用await + try/catch的写法即可,连接池创建失败的错误会直接被外层catch块捕获,你可以在catch内自定义报错信息:

try {
    // Create a connection pool which will later be accessed via the
    // pool cache as the 'default' pool.
    await oracledb.createPool({
        user: dbConfig.user,
        password: dbConfig.password,
        connectString: `${dbConfig.host}:${dbConfig.port}/${dbConfig.serviceId}` 
    })
    // 执行到这里说明连接池创建成功
    console.log('Connection pool started');
} catch (err) {
    // 捕获createPool抛出的所有错误,自定义报错信息
    const customErr = `Connection pool failed with ${err.message}`;
    console.log(customErr);
    // propagate
    throw customErr;
}

如果确实需要保留回调写法,需要手动将回调包装成Promise再配合await使用,但这种写法冗余,不推荐使用。

内容的提问来源于stack exchange,提问作者Greggz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 04:21:00