Skip to content

[Client] Error event VS promise rejection VS callback error. Not coherent behaviour  #1527

Closed
@marqu3z

Description

@marqu3z

Hi, i struggled a while around this topic and i'm not sure the current behaviour is the intended one.

Here's a code example:

const {Client} = require('pg')

let client = new Client('wrong-address')

/* Set a global error event listener to handle possible uncaught errors */
client.on('error', () => {
  console.log('error catched from error event')
})

/* 
   Try to connect and catch the error with a callback pattern. 
   The database address is wrong and it will reject 
*/
client.connect((err) => {
  if (err) {
    console.log('error catched from callback')
  }
})

The result from the console is:

error catched from callback

The error has been catched inside the callabck.
The Client error event is not fired.
I assume it is a correct behaviour since the error has been handled inside the callback.

Then i tried to use the promise pattern instead of the callback.

/* 
  Try to connect and catch the rejection. 
  The database address is wrong and it will reject 
*/
client.connect().catch(() => {
  console.log('error catched from promise rejection')
})

Result:

error catched from error event
error catched from promise rejection

The error is fired also on the client error listener.
I'm not sure if this is intended but it is quite confusing.
I'm explicitly catching it inside the promise .catch() during a connection but it will also be handled by the general error listener causing the error to be managed by two different functions.

If i'm handling the error in a specific context within the function execution (calback or promise) i would expect to not deal with the same error inside the client error event.

But regardless of what the correct approach could be, at least it should be coherent and behave in the same way whether a promise or a callback has been used to handle the error.

node-postgres: v7.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions