diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc index 8341b27a4fa0..f2d93aa2f588 100644 --- a/src/node_sqlite.cc +++ b/src/node_sqlite.cc @@ -3357,6 +3357,16 @@ int Database::TraceCallback(unsigned int type, return 0; } + // The profile callback also runs when a statement fails and when it is + // reset, both of which can happen while a JavaScript exception is already + // pending: a throwing SQL function, or a row value that cannot be converted. + // Publishing here would enter V8 with that exception still set. Debug + // builds then abort in Invoke, and release builds drop the user's error or + // replace it with an empty ERR_SQLITE_ERROR. + if (!env->can_call_into_js() || env->isolate()->HasPendingException()) { + return 0; + } + // Entered before building the payload below, because allocating it can // trigger a garbage collection that SQLite is not prepared for. CallbackDepthGuard guard(db); diff --git a/test/parallel/test-sqlite-diagnostic-channel.js b/test/parallel/test-sqlite-diagnostic-channel.js index eb9461f337d5..20df20edfe16 100644 --- a/test/parallel/test-sqlite-diagnostic-channel.js +++ b/test/parallel/test-sqlite-diagnostic-channel.js @@ -234,4 +234,38 @@ suite('sqlite.db.query diagnostics channel', () => { { __proto__: null, x: 1 }, ]); }); + + it('does not replace an exception that is already pending', (t) => { + using db = new Database(':memory:'); + let calls = 0; + const handler = () => { + calls++; + }; + dc.subscribe('sqlite.db.query', handler); + t.after(() => dc.unsubscribe('sqlite.db.query', handler)); + + db.function('boom', () => { + throw new Error('boom'); + }); + assert.throws(() => db.prepare('SELECT boom()').get(), { + message: 'boom', + }); + + db.exec('CREATE TABLE t (a INTEGER)'); + db.exec('INSERT INTO t VALUES (9223372036854775807)'); + assert.throws(() => db.prepare('SELECT a FROM t').get(), { + code: 'ERR_OUT_OF_RANGE', + }); + assert.throws(() => db.prepare('SELECT a FROM t').all(), { + code: 'ERR_OUT_OF_RANGE', + }); + + // A query that does not throw is still published. + const before = calls; + assert.deepStrictEqual(db.prepare('SELECT 1 AS x').get(), { + __proto__: null, + x: 1, + }); + assert.ok(calls > before); + }); });