Home > Enterprise >  Remove brackets in V8 prepareStackTrace
Remove brackets in V8 prepareStackTrace

Time:01-23

I am working on reformatting stack traces in Node using prepareStackTrace. It evidently (node 18 ) encases the return value in square brackets. I was able to use the backspace unicode to remove first one but no success with last. Suggestions and ideas why this was done? it's not just the stack trace that this function handles but also the error name so everything is encased in brackets.

Error.prepareStackTrace = (err, stack) => {
  return 'foo'
}

console.log(err) prints the stack as:

[foo]

You'll notice that you lost the name and message as well which is weird for a function called stack trace. It has to be re-added manually but thats workable though the entire thing is still in brackets.

Heres a sandbox https://codesandbox.io/s/gifted-visvesvaraya-9dokms?file=/src/index.js - look at terminal output.

CodePudding user response:

First observation: this seems to be an oddity of the Node console implementation. V8 on its own (in the form of the d8 shell) behaves differently, and even the Node REPL behaves differently.

Second observation: console.log(new Error("...").stack) prints foo without square brackets.

CodePudding user response:

Well, your snippet as posted is still invalid:

Welcome to Node.js v18.13.0.
Type ".help" for more information.
> Error.prepareStackTrace(err, stack) { return 'foo' }
Uncaught Error.prepareStackTrace(err, stack) { return 'foo' }
                                    ^

SyntaxError: Unexpected token '{'
>

Which is to be expected because that is, indeed, invalid syntax.

I'm going to guess that you meant to spell out an assignment, so let's try that again:

Welcome to Node.js v18.13.0.
Type ".help" for more information.
> Error.prepareStackTrace = function(error, stack) { return "foo"; }
[Function (anonymous)]
> console.log(err)
Uncaught foo

That seems to be exactly what you'd expect to get.

If you did something different that caused you to see something else, please provide accurate and complete repro instructions. Don't make me guess what you meant to write.

  • Related