Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

334
Vistas
Is a Try/Catch Redundant in a Node.js MySQL Query?

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.")
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.")
    }

});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda