node-learnin'

14 thoughts
last posted June 27, 2015, 9:24 p.m.

1 later thought

0

Node debugging hack

I was getting stack traces from errors that had been passed back to several callbacks, and I couldn't figure out where the calling code was that started off the chain. So I came up with this ugly beast.

function injector(callback) {
    var trace = new Error().stack;
    return function(err, res) {
        if (err) {
            err.injection += trace + '\n' + new Error().stack + '\n\n';
        }
        callback(err, res);
    };
}

Which can then be called like so with async:

var myLib = require('myLib');

async.each([
    function oneThing(cb) {
        myLib.doSomethingAsync(injector(cb));
    },
    function twoThing(cb) {
       myLib.aDifferentAsync(injector(cb));
    }
], function(err, res) {
    // handle results
});

In injector, the first call to new Error().stack will tell you whether it was oneThing or twoThing that ultimately generated the error. The second will tell you where in myLib the call came from.

Before this my stack traces only had information from deep in the dependency tree.

I haven't tried this yet on a callback with an error that's already been injected. I wonder if all that info would be needed or if the most recent call would be enough.


Just realized, since I'm not using this in production, I can do this instead:

function injector(callback) {
    var trace = new Error().stack;
    return function(err, res) {
        if (err) {
            console.trace(trace);
        }
        callback(err, res);
    };
}

12 earlier thoughts