Good async stack traces with a custom `.then` method?

36 views
Skip to first unread message

Kannan Goundan

unread,
Feb 10, 2021, 10:47:02 PM2/10/21
to v8-users
I'm using a DB query builder library that presents a chaining-style API, e.g.:

    const query = db.select(...).from(...).where(...);

The query is executed when you `await` it, e.g.:

    const results = await query;

That is implemented with a `.then` method on the query object.  That method builds the query string, then calls a user-defined function to actually execute the query: https://github.com/Ff00ff/mammoth/blob/144b46482608f9c1582f33832e234e2b6dfda2fc/src/select.ts#L155

My problem: if the user-defined function returns a rejected promise (i.e. there was an error running the query) the resulting exception's stack trace is truncated.  It doesn't have the usual V8 async stack trace goodness.

Standalone example:

    function gap() {
        return new Promise(resolve => setTimeout(resolve, 1));
    }

    // A class that has it's own 'then' method.
    class Query {
        constructor(f) {
            this.f = f;
        }
        then(onFulfilled, onRejected) {
            this.f()
                .then(r => onFulfilled ? onFulfilled(r) : r)
                .catch(onRejected);
        }
    }

    async function f1() {
        try {
            await f2();
        }
        catch (err) {
            console.log('err', err);
        }
    }
    async function f2() {
        await gap();
        await f3();
    }
    async function f3() {
        await gap();
        await new Query(async () => { throw new Error('query error'); });
    }

In the Chrome 88.0.4324.150 (Mac):

    > await f1();
    err Error: query error
        at Query.f (<anonymous>:31:45)
        at Query.then (<anonymous>:11:18)

I get the same thing in Node 14.15.0, which is what I'm actually using.

In Firefox 85.0.2 (Mac):

    await f1();
    err Error: query error
        f3 debugger eval code:31
        then debugger eval code:11
        promise callback*f3 debugger eval code:31
        f2 debugger eval code:27
        f1 debugger eval code:19
        <anonymous> debugger eval code:2
        <anonymous> debugger eval code:3

Is there a way to modify the DB query builder library to work well with V8 async stack traces without modifying the library's public API?
Reply all
Reply to author
Forward
0 new messages