Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda