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

500
Visualizações
Handling errors and recoverying with node pg (postgres) client

I am using node module pg in my application and I want to make sure it can properly handle connection and query errors.

The first problem I have is I want to make sure it can properly recover when postgres is unavailable.

I found there is an error event so I can detect if there is a connection error.

import pg from 'pg'
let pgClient = null
async function postgresConnect() {
  pgClient = new pg.Client(process.env.CONNECTION_STRING)
  pgClient.connect()

  pgClient.on('error', async (e) => {
    console.log('Reconnecting')
    await sleep(5000)
    await postgresConnect()
  })
}

I don't like using a global here, and I want to set the sleep delay to do an small exponential backoff. I noticed "Reconnecting" fires twice immediately, then waits five seconds and I am not sure why it fired the first time without any waiting.

I also have to make sure the queries execute. I have something like this I was trying out.

async function getTimestamp() {
  try {
    const res = await pgClient.query(
      'select current_timestamp from current_timestamp;'
    )
    return res.rows[0].current_timestamp
  } catch (error) {
    console.log('Retrying Query')
    await sleep(1000)
    return getTimestamp()
  }
}

This seems to work, but I haven't tested it enough to make sure it will guarantee the query is executed or keep trying. I should look for specific errors and only loop forever on certain errors and fail on others. I need to do more research to find what errors are thrown. I also need to do a backoff on the delay here too.

It all "seems" to work, I don't want to fail victim to the Dunning-Kruger effect. I need to ensure this process can handle all sorts of situations and recover.

over 4 years ago · Santiago Trujillo
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