【问题标题】:Node mysql2 async-await try catch节点 mysql2 async-await try catch
【发布时间】:2019-03-14 01:17:24
【问题描述】:

我的问题是关于在 Nodejs 中处理异步等待 mysql 查询中的错误。我正在使用 mysql promise wrapper 在 nodejs 中创建一个连接池。

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
host: '192.168.0.1',
  user: 'root',
  database: 'h2biz_18_dev',
  waitForConnections: true,
  connectionLimit: 100,
  queueLimit: 0,
  password : 'abc'
})

catch 块内的连接释放不能调用,因为抛出错误说

Cannot read property 'release' of undefined

如果查询执行抛出错误,是否需要释放catch块中的连接?如果是这样,在使用 mysql2 的异步等待中释放连接和捕获错误的正确方法是什么?

router.post('/getHolidaysOfYear',async function (req, res, next) {      
    var conn;

try{
    conn = await pool.getConnection();
        // Do something with the connection
    var promise1 = conn.execute(`
    SELECT 
        CALENDAR.*
    FROM
        hrm_calendar_holiday_policy1 CALENDAR
    `);
    const values = await Promise.all([promise1]);
    conn.release();
    return res.status(200).send({success:true, data:values[0][0]});
}

catch(err){
    logger.error(API_NAME + 'error :' + err);
    conn.release();
    return res.status(500).send({success:false, message:'Query Error'});
}
});

【问题讨论】:

    标签: node.js promise async-await node-mysql2


    【解决方案1】:

    看起来甚至在 conn 初始化之前就发生了错误,所以在 pool.getConnection(); 内部。

    因此,在您的 catch 块中,变量 conn 为 null,因此它不能/不必被释放。

    你可以这样做:

    catch(err){
        logger.error(API_NAME + 'error :' + err);
        if(conn !== undefined) //This will check if the conn has already be initialized
            conn.release();
        return res.status(500).send({success:false, message:'Query Error'});
    }
    

    【讨论】:

    • 谢谢。会的。
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2018-06-21
    • 2018-07-05
    • 2018-05-29
    • 2021-08-28
    • 2017-11-23
    相关资源
    最近更新 更多