please help.
I'm making use of the node-mysql2 library
I have SQL queries and whenever a query is run and some variables are null in that query it triggers this error. This is usually when the session variables are null. AgentID=Null or DealerID=Null.
The error originates from the mysql2 connection.js file
C:\inetpub\wwwroot\pavstockallocatebot\node_modules\mysql2\lib\connection.js:538
if (sql.constructor === Commands.Query) {
^
TypeError: Cannot read properties of undefined (reading 'constructor')
Where it is triggered:
query(sql, values, cb) {
let cmdQuery;
if (sql.constructor === Commands.Query) {
cmdQuery = sql;
} else {
cmdQuery = Connection.createQuery(sql, values, cb, this.config);
}
this._resolveNamedPlaceholders(cmdQuery);
const rawSql = this.format(cmdQuery.sql, cmdQuery.values !== undefined ? cmdQuery.values : []);
cmdQuery.sql = rawSql;
return this.addCommand(cmdQuery);
}
It freezes my whole app. and doesn't allow me to restart the app. How can I add an error handler that will check if the variables are undefined or null to avoid ever getting this error. When I do get this error to handle it appropriately.
CodePudding user response:
There are many coding styles, but this is one solution.
It's crashing the app because it is an "uncaught" error. So let's catch it.
try {
//this will error
if (sql.constructor === Commands.Query) {}
} catch(error) {
// then you can console.log the error here
// and do something else.
}
Ideally you would check to see if sql
is truthy and that your sql connection has been established before any sort of logic can touch this part of the code. But that can evolve into a bigger conversation around scaffolding and server logic architecture.
CodePudding user response:
Check if this helps
if(sql && sql.constructor === Commands.Query)
or
if(sql?.constructor === Commands.Query)