Replies: 1 comment
-
Hey, @fewbulets. Using callbacks, we can handle errors like: import mysql from 'mysql2';
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
});
pool.execute('SELEC 1 + 1', (err, rows) => {
if (err instanceof Error) {
console.log(err.message); // You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELEC 1 + 1' at line 1
return;
}
console.log(rows);
});
Using promises, we can handle errors like: import mysql from 'mysql2/promise';
try {
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
});
const [rows] = await pool.execute('SELEC 1 + 1');
console.log(rows);
} catch (err) {
err instanceof Error && console.log(err.message); // You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELEC 1 + 1' at line 1
}
To catch connection errors, I recommend this discussion:
I'll bring it here from mysqljs error handling section:
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi Sidorares,
Great job indeed, thanks!
However... I'm running into an issue trying to handle possible errors that may arise while using the .execute() method.
From the 'prepare.js' example, I can read as follows:
// execute will internally call prepare and query connection.execute( 'SELECT * FROM
tableWHERE
name= ? AND
age> ?', ['Rick C-137', 53], (err, results, fields) => { console.log(results); // results contains rows returned by server console.log(fields); // fields contains extra meta data about results, if available
So, what about the err argument ?
I've set up a pool (named pool) exported as a promise.
In my code, using:
const myFunction = async () => { const query =
SELECT * FROM table1;const [result, _] = await pool.execute(query) ...
works fine, but I may not catch errors even in a try / catch block.
On the other hand, using:
const dbGetAllServices = async () => { const query =
SELECT * FROM table1;await pool.execute(query, undefined, (err, res) => { console.log('RES: ', res) console.log('ERR: ', err) ...
will fail, .
I was assuming this to actually log something ('promise pending' or whatsoever) but I can't get any result nor error with this syntax. What's wrong with it ? isn't it working because of the 'pool' connection ?
And btw, what king of errors is the 'err' argument suppose to provide us with ? connection-wide, database-wide, table errors only...?
Looking forward :-)
Beta Was this translation helpful? Give feedback.
All reactions