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

449
Vistas
Retry connection postgres Nodejs

I am using a postgres database for my express web server. I am using the 'pg' library to execute queries on this database.

Here is my connection method :

const db = new Client({
    user: 'xxx',
    host: 'xxx',
    database: 'xxx',
    password: 'xxx',
    port: xxx,
})
db.connect(err => {
    if (err) {
        console.error('connection error', err.stack)
    } else {
        console.log('connected')
    }

Then to execute a request I do this:

db.query(MY_REQUEST, function (err, data) {
            if (err) throw err;
            res.render('hello/world', {
                title: 'Hello',
                data: data.rows
            });
        });`

It all works perfectly. But after several minutes without using my website, my connection to the db times out, and I get the following error:

node:events:355
throw er; // Unhandled 'error' event
       ^
Error: Connection terminated unexpectedly
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:484:28)
at Connection.emit (node:events:378:20)
at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:58:12)
at Socket.emit (node:events:378:20)
at TCP.<anonymous> (node:net:665:12)
Emitted 'error' event on Client instance at:
at Client._handleErrorEvent (/usr/src/app/node_modules/pg/lib/client.js:319:10)
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:149:16)
at Object.onceWrapper (node:events:484:28)
[... lines matching original stack trace ...]
at TCP.<anonymous> (node:net:665:12)

How could I do to reconnect automatically when the connection is cut or when a request fails?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You should attach an error-handler in order to prevent the unhandled error crashing your app. It's as simple as:

db.on('error', e => {
  console.error('DB error', e);
});

As to why the error happens we need more details, looks like it could be a connection reset due to idle-timeout?

over 4 years ago · Santiago Trujillo Denunciar

0

You can create a function to control if you're connected to database or not, before you continue with your main function.

Create a function for controlling database connection status, reconnecting etc. and before you run a database related function, first start that middle function and wait for result, after that you can continue using database again.

If you want(which should be prefered way mostly), create that middle function as an async function and return a promise, when using that function wait for that function.

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