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

184
Visualizações
How to throw an Error inside pg pool query in Express JS?

I am facing trouble when I try to throw an Error (to mark if there are no username) inside pool query. What I am expect is the error was catch by checkUsername and make it standard json response. But, I always get an error like this:

error details

Here is my code in controller:

const checkUsername = (req, res) => {
  const service = new AuthService()
  try {
    service.chekcUsernameIsExist(req.body.username, res)

    return res.status(200).send('Username is exist')
  } catch (error) {
    const response = {
      status: false,
      message: error.message,
      error_code: 400
    }
    return res.status(400).send(response)
  }
}

And here is my code in service:

class AuthService {
  chekcUsernameIsExist (username) {
    const query = `select * from admins where username = '${username}';`

    pool.query(query, (err, results, release) => {
      if (err) {
        throw err
      } else if (results.rowCount !== 0) {
        console.log('Username is exist')
      } else {
        console.log('Username is not exist')
        throw new Error('Username is not exist')
      }
    })
  }
}

I try to add try catch block inside checkUsernameIsExist but still got the same problem. At the stupid, I add a variable to which have value 1, 2, or 3 to mark is username exist, not exist, or other error.

about 4 years ago · Juan Pablo Isaza
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