Search code examples
node.jspromiseasync-awaitnode-mysql2

Node mysql2 async-await try catch


My Question is about handling errors in async-await mysql queries in Nodejs. I'm using mysql promise wrapper to create a connection pool in 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'
})

inside catch block connection release cannot be called as error is thrown saying

Cannot read property 'release' of undefined

Is it needed to release the connection in catch block if an error is thrown by query execute? if so what is the proper way to release connection and catch errors in async await with 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'});
}
});

Solution

  • It looks like an Error occurs even before the conn is initialized, so inside pool.getConnection();.

    Therefore in your catch-block the variable conn is null and therefore it can´t / doesn't have to be released.

    You could do something like :

    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'});
    }