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

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

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 Relatório

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 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