在 node-pg 中获取信息丰富的堆栈跟踪

Yan*_*nnP 7 database postgresql node.js node-postgres typescript

我正在node-pg与打字稿一起使用。

我有一个来自文档的 getPool 实用程序https://node-postgres.com/features/pooling

export const getPool = (config?: PoolConfig) => {
  const pool = new Pool(config);
  pool.on('error', (err, client) => {
    console.error('Unexpected error on idle client', err);
    process.exit(-1);
  });
  return pool;
};
Run Code Online (Sandbox Code Playgroud)

我在异步/等待上下文中像这样使用它

const pool = getPool();
await pool.query('my sql query here...');
Run Code Online (Sandbox Code Playgroud)

当我有一个无效的 SQL 查询时,我会收到此类错误:

error: null value in column "foo" violates not-null constraint

  at Parser.parseErrorMessage (node_modules/pg-protocol/src/parser.ts:357:11)
  at Parser.handlePacket (node_modules/pg-protocol/src/parser.ts:186:21)
  at Parser.parse (node_modules/pg-protocol/src/parser.ts:101:30)
  at Socket.<anonymous> (node_modules/pg-protocol/src/index.ts:7:48)
Run Code Online (Sandbox Code Playgroud)

注意:我会理解是否是pool.on('error')s 回调窃取了我的堆栈跟踪,但错误没有以Unexpected error on idle client

请注意,在堆栈跟踪中没有任何行指向我的代码库中的文件。

我的问题是,我的代码库中有数百个查询,并且我希望能够跟踪调用失败的行pool.query()。这对于查找哪个查询触发了错误有很大帮助。

预期的 :

error: null value in column "foo" violates not-null constraint

  at ...
  at mycodebase/src/myfile.ts:42
Run Code Online (Sandbox Code Playgroud)

MiF*_*MiF 1

我使用 dirty hack ( patch Pool.prototype),但它对我有用:

const originalPoolQuery = Pool.prototype.query;
Pool.prototype.query = async function query(...args) {
    try {
        return await originalPoolQuery.apply(this, args);
    } catch (e) {
        // All magic is here. new Error will generate new stack, but message will copyid from e
        throw new Error(e)
    }
}

// After hack create pool and good luck
const pool = new Pool({})

await pool.query('SELECT * FROM ...')
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Stacktrace 会提供更多信息。

我认为这pool.on('error', cb)不是为了捕获查询错误,而是为了连接错误(我不确定)