I'm working on some algorithms that explore a tree (via recursion) to inspect and transform it. I'm using a number of helper functions to recurse: they validate input and output data, log stuff, handle some exceptions and so on and so forth.
When there's an error, I rely on the stack trace to figure out what's happening and fix it. However the stack trace is polluted by those recursion helper.
Here a minimal example (uncorrelated to my program) that shows the issues with the stack trace pollution:
function sum(list) {
if (list.length===0) { throw new Error("not yet implemented"); }
const [head, ...tail] = list;
return helper1(()=>{
return head + sum(tail);
});
}
function helper1(f) {
try {
return helper2(f);
} catch(e) {
// here I'm supposed to try to handle the error
throw e;
}
}
function helper2(f) {
// here I'm supposed to increase indentation for loged messages...
const r = f();
// ...and now decrease it
return r;
}
try {
console.log(sum([7, 2, 3, 8]));
} catch(e) {
console.error(e.stack);
}
For each recursive call to sum
, the stack trace contains additional calls to helper1
, helper2
and the closure passed to helper1
by sum
. In the case of my program, I have 8 of those functions polluting the stack trace for every recursive step.
Is there any way to silence or hide those helper functions from the stack trace?
If the issue is primarily with debugging, there is a solution: the devtools script ignore-list. This allows you to remove the functions of no interest from the callstack trace view. See also How do I skip external code when debugging in VS Code, Is there a way to hide 3rd party JS function calls in stack trace in chrome or firebox debugger?, Avoid irrelevant files while debugging in Chrome not working and How to ignore internal ReactJS code in the call stack while debugging ReactJS.
If you actually need to the stack for your logic, e.g. to locate your position in the tree datastructure, I would recommend to drop that approach and rather pass through a path
array (or keep a global variable on which you push
and pop
the relevant segments).