node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Add a specific error class and error codes

Open rightaway opened this issue 3 years ago • 1 comments

Errors that come from postgres queries are wrapped in pg.DatabaseError, so we can do instanceof checks. And they have the standard postgres metadata like code that comes from the postgres error, so we can compare against that. Error handling code can be very reliable and clear for these.

But errors at the client level like https://github.com/brianc/node-postgres/blob/21ccd4f1b6e66774bbf24aecfccdbfe7c9b49238/packages/pg/lib/client.js#L563 are plain Error objects and have no code so we have to do comparisons on the error message. Can there be a new class like pg.ClientError that has stable error codes for all types of errors?

e = new pg.ClientError('Client has encountered a connection error and is not queryable')
e.code = 'CONN_ERR_NOT_QUERYABLE'

Then in our code we can first see if an error caught at a higher level belongs to node-postgres with e instanceof pg.ClientError, and we can take specific action with e.code === 'CONN_ERR_NOT_QUERYABLE'.

rightaway avatar Mar 18 '22 10:03 rightaway

That will improve the DX significantly. And sounds like a really easy thing to do. Just define a new PgError class and update all of the throw statements. @brianc would you consider a pull request for this? Thanks

Louis-Tian avatar Sep 07 '22 06:09 Louis-Tian

@brianc Following up on @Louis-Tian asking about a pull request for this.

rightaway avatar Dec 16 '22 03:12 rightaway