I am setting up a system that will query a MySQL database for registering and deleting staff and such. I was just wondering if there is a need to have the query in a try catch block or if it is simply redundant. I have an example below. My understanding is that this will throw an error but not crash the system as it will, as a try/catch does, catch the error and let the server remain functional.
var con = mysql.createConnection({
host: 'mysql1',
user: 'root',
database: 'assignment',
password: 'admin'
});
let sqlQuery = `INSERT INTO CBOdb (staffName, staffID, staffPassword, time) VALUES ('${staffName}', '${staffID}', '${staffPassword}', NOW())`;
try {
con.query(sqlQuery, function(err, result) {
if (err) {
throw err;
} else {
res.send(0)
}
})
} catch {
res.send(1) //"**Error ecounterd, staff not registerd**\nPlease contact system Administrator.")
}
CodePudding user response:
Is a Try/Catch Redundant in this Node.js MySQL Query?
Yes, it is unnecessary. Errors from the query are not communicated back via synchronous exceptions that you can catch with try/catch
. They are communicated back via the err
argument to the callback.
As has been mentioned in the comments, there are a couple different versions of the mysql module for nodejs. You are using the original version based on plain callbacks. There is another version of the module named mysql2 that supports promises and this gives you some more modern ways of calling mysql and handling errors using promises, await
and try/catch
.
Here's an example of using await
and catching errors with try/catch using the mysql2/promise interface.
const mysql = require('mysql2/promise');
app.get("/somePath", async (req, res) => {
// this needs to be inside an async function so you can use await
const con = await mysql.createConnection({ ... });
let sqlQuery = `INSERT INTO CBOdb (staffName, staffID, staffPassword, time) VALUES ('${staffName}', '${staffID}', '${staffPassword}', NOW())`;
try {
const result = await con.query(sqlQuery);
res.send(0)
} catch(e) {
console.log(e);
res.send(1); //"**Error ecounterd, staff not registerd**\nPlease contact system Administrator.")
}
});