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

194
Vistas
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.

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