brianc / node-pg-pool

A connection pool for node-postgres
MIT License
180 stars 64 forks source link

Pool with Promises in Lambda Propagates to Node #33

Closed mladlow closed 6 years ago

mladlow commented 8 years ago

I am configuring a Pool with Bluebird as the promise library for use in an AWS Lambda handler: const pool = new Pool({...config, Promise: Promise});

My handler makes 3 asynchronous calls to the database. If the calls fail, although I have a catch block in my Promise chain, and although the catch block catches and handles the error, the Node process exits regardless.

return makeDbCall(params)
.then((dbResult) => {
// do good stuff
})
.catch((dbError) => {
// handle error, return Promise.resolve
});

Is it possible to stop the error from the query from killing my Node process?

I've tried something like:

query(sql, bind, (error, result) => {
if (error) {
return;
// return Promise.resolve(error);
// return Promise.reject(error);
}
return Promise.resolve(result);
});

But the error still propagates and kills the Node process.

calebboyd commented 7 years ago

Hi @mladlow, Pool is an EventEmitter -- when uncaught errors occur on EventEmitters they will throw at the process level and crash node.

See the docs for reference

mladlow commented 7 years ago

@calebboyd my understanding from reading the docs was that calling query with a callback (as in the second code snippet) would catch the uncaught error, but the error seemed to propagate even though I provided the error-handling callback.

If that second code snippet is insufficient, how can I properly catch the error from the EventEmitter?

calebboyd commented 7 years ago

I would try setting an error handler on the Pool object itself.

mladlow commented 7 years ago

Wouldn't that be something like:

import {Pool} from 'pg';
...
const pool = new Pool({...config}, Promise: Promise}); // Promise is from Bluebird here
pool.on('error', (error) => {
  // do stuff, but should count as "handling" the error?
});

We have this handling, but it either wasn't triggering at all, or wasn't stopping the error from propagating (I don't remember - it was a while ago, and we've since worked around the problem). Do I need to explicitly import from pg-pool in order to catch the error?

charmander commented 7 years ago

This was a bug in pg-pool 1.5; upgrade to 1.6.