1

When I do console.error('Custom Error') I get a nice trace of where it came from

For Example:

func1();

function func1() {
  func2();
}

function func2() {
  func3();
}

function func3() {
  console.error('Custom Error');
}

I get:

JS Custom Error

How can I do this without producing an error, more like console.log()?

Jack
  • 1,893
  • 1
  • 11
  • 28
  • 1
    Can I ask what your use case is? Are you writing a logger of some sort? – ggorlen Dec 12 '20 at 23:21
  • @ggorlen I'm using a proxy to detect the change of property and call a function to update something. I'm using `console.error` so I can see exactly where this property was changed in the code for better debugging. Since its not an error, I'd like it not to appear as one if possible – Jack Dec 12 '20 at 23:23
  • @ggorlen prefect should have thought about that. It worked great, just have a fake error for it to catch as it won't catch `console.error()` – Jack Dec 12 '20 at 23:27
  • Ah, OK, then `console.log(Error("Custom Error"))` seems like the way to go. No need to throw it and catch in the global scope as I suggested or anything like that. – ggorlen Dec 12 '20 at 23:30
  • @ggorlen That worked even better, there probably is not a way to remove the `Error: ` from `Error: Custom Error` is there? – Jack Dec 12 '20 at 23:33
  • 1
    Sure, maybe `console.log(Error().stack.slice(6))`? Even better: `console.trace("foo")` – ggorlen Dec 12 '20 at 23:35
  • @ggorlen If you post an answer I can accept it, ty for your help – Jack Dec 12 '20 at 23:38

1 Answers1

0

You could use console.trace() instead of console.error().

This is what you see on the console with console.trace():

Trace
func3 @ js:24
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12

And this with console.error():

Custom Error
console.error   @   snippet-javascript-console.min.js?v=1:1
func3   @   js:23
func2   @   js:19
func1   @   js:15
(anonymous) @   js:12

If you want to get the stack trace into a variable instead of just logging it, you can use Error.captureStackTrace(targetObject) or Error().stack, but both are non-standard:

func1();

function func1() {
  func2();
}

function func2() {
  func3();
}

function func3() {
  const fakeErrorObject = {};
  
  Error.captureStackTrace(fakeErrorObject)
  
  const captureStackTraceTrace = fakeErrorObject.stack;
  const errorStackTrace = Error('Foo').stack;
  
  console.log(captureStackTraceTrace.replaceAll('at', ''));
  console.log(errorStackTrace.replaceAll('at', ''));
}
.as-console-wrapper {
  max-height: none !important;
}
Danziger
  • 19,628
  • 4
  • 53
  • 83