0
votes

Scenario 1: postgres service not running. node start. rest calls times out => no issues

Scenario 2: postgres service not running. node start. postgres service start. rest calls work => no issues

Scenario 3: postgres service not running. node start. postgres service start. rest calls work. postgres service stop => node crash.

Stack trace when this happens is given below:

error: terminating connection due to administrator command at Connection.parseE (...\express.js\node_modules\pg\lib\connection.js:553:11) at Connection.parseMessage (...\express.js\node_modules\pg\lib\connection.js:378:19) at Socket. (...\express.js\node_modules\pg\lib\connection.js:119:22) at emitOne (events.js:116:13) at Socket.emit (events.js:211:7) at addChunk (_stream_readable.js:263:12) at readableAddChunk (_stream_readable.js:250:11) at Socket.Readable.push (_stream_readable.js:208:10) at TCP.onread (net.js:594:20)

I am using Postgres Pool with the following config:

const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'sampleDB',
    password: 'password',
    port: 5432,
    max: 1,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000,
})

How do I handle this case so that node won't crash and can go back to Scenario-1 and then move to Scenario-2 ?

1
Catch the error. The appropriate SQLSTATEs are 57014, 57P01 and 57P02.Laurenz Albe
@LaurenzAlbe Thanks. I have couple of Questions related to this. 1: How did you get the codes? 2: Is this an acceptable approach in a production environment?iam thadiyan
java.sql.SQLException has a getSQLState() method. This is the best way to distinguish between different errors. Parsing the message text is a bad idea.Laurenz Albe

1 Answers

2
votes

After going through the documentation of node-postgres(link), I figured out a way to capture this error and avoid node crash.

pool.on('error', (err, client) => {
    console.log('postgres connection error : ' + err)
})

Adding the above code will allow node to handle the error and not crash.