javascript print stack trace code example

Example 1: js trace function call

// details can be found here: https://2ality.com/2017/11/proxy-method-calls.html

function traceMethodCalls(obj) {
    const handler = {
        get(target, propKey, receiver) {
            const targetValue = Reflect.get(target, propKey, receiver);
            if (typeof targetValue === 'function') {
                return function (...args) {
                    console.log('CALL', propKey, args);
                    return targetValue.apply(this, args); // (A)
                }
            } else {
                return targetValue;
            }
        }
    };
    return new Proxy(obj, handler);    
}

const objWithFunction = {
  methodA: (a) => { return a; }
}

const proxyWithTrace = traceMethodCalls(objWithFunction);

Example 2: javascript get stack trace

try {
    throw "Could not parse that text!";
} catch(e) {
    console.log(e.stack);  //log the stack trace to console
}

Example 3: console trace js

console.trace( [...any, ...data ]);