The description on this page is certainly a bit complicated, here's how to do it:
Error.prepareStackTrace = function(error, stack) { return stack; }; var someObj = { someMethod : function () { crash(); } } function bar(barArg) { someObj.someMethod(); }; function foo(fooArg) { bar("barArgString"); }; function getTrace(e) { var stack = e.stack; var trace = ""; for (var i = 0; i < stack.length; i++) { var frame = stack[i], func = frame.getFunction(); trace += "\r" + frame.getThis() + "." + frame.getFunctionName(); } return trace; } try { foo("fooArgString"); } catch (e) { alert("trace from catch(): " + getTrace(e)); }
This will show:
trace from catch(): [object Object].someObj.someMethod [object Window].bar [object Window].foo [object Window].
The last frame is a global region (without a function name).
Essentially your overriding of the prepareStackTrace () method causes error.stack to become what you return from prepareStackTrace (). The trick is that the second argument to prepareStackTrace () is an array of CallSite objects — objects that support getThis (), getFunctionName (), etc.
The above code overrides prepareStackTrace () so that it returns an Array of CallSite object (the "stack" parameter above), so that if you try .catch Error, Error.stack will contain a CallSite array instead of the usual stack trace in string form . Another approach would be to process CallSite objects inside your prepareStackTrace () replacement and return your alternative stack trace as a string.
Please note that CallSite objects are really very successful. Try making frame.toString () or just trying to warn (frame) (implicitly this includes toString ()) and it crashes and the Chrome developer tools show no errors.
Charles Kendrick Jun 08 2018-12-12T00: 00Z
source share