When using the mysql2/promise wrapper, error handling is performed using standard try-catch blocks. This applies to createConnection, createPool, createPoolCluster, execute, and query methods.
import mysql from 'mysql2/promise';
// For createConnection
try {
const connection = await mysql.createConnection({
host: '',
user: '',
database: '',
});
} catch (err) {
if (err instanceof Error) {
console.log(err);
}
}
// For createPool
const pool = mysql.createPool({
host: '',
user: '',
database: '',
});
try {
const connection = await pool.getConnection();
} catch (err) {
if (err instanceof Error) {
console.log(err);
}
}
// For createPoolCluster
const poolCluster = mysql.createPoolCluster();
poolCluster.add('NodeI', {
host: '',
user: '',
database: '',
});
try {
await poolCluster.getConnection('NodeI');
} catch (err) {
if (err instanceof Error) {
console.log('createConnection error:', err);
}
}
// For execute and query
// Works for createConnection, createPool, and createPoolCluster
try {
const [rows] = await connection.execute('SELEC 1 + 1');
console.log(rows);
} catch (err) {
if (err instanceof Error) {
console.log('execute error:', err);
}
}
try {
const [rows] = await connection.query('SELEC 1 + 1');
console.log(rows);
} catch (err) {
if (err instanceof Error) {
console.log('query error:', err);
}
}