I am new to Node.js and I have the following code below:
const mysql = require('mysql');
async function insertNewRecord(record) {
const connectionUrl = 'mysql://root:mypassword@mydatabasehost:3306/mydb';
const pool = mysql.createPool(connectionUrl);
pool.on('connection', function (conn) {
console.log('*******on connection***********');
});
pool.on('error', function () {
console.log('****POOL CONNECTION ERROR***');
});
await pool.query('INSERT INTO users SET ?', record);
}
async function doProcess() {
try {
//construct record object
insertNewRecord(record)
} catch (error) {
console.log(error);
}
}
I purposely used the wrong database host name to see if the error would be caught and logged, but I saw no log. I was expecting to see POOL CONNECTION ERROR in the logs but it didn't show up. No error was caught either from the catch statement.
Am I doing something wrong? I did my own research and the pool.on lines you see in the codes is what I have tried to add, but doesn't seem to work. Am I doing error handling the correct way?
insertNewRecord(record)is an asynchronous function. If you don't useawaitwith it node won't wait for the function to complete, and you won't see the error.