10

How do I print the stack trace of an Exception in the chrome devtools from my code?

I tried the following:

 function doSomething() { 
     undefined(); // This throws an exception
 }

 try {
      doSomething();
 } catch (e) {
      console.error("Exception thrown", e);
 }

But this yields the following result:

 Exception thrown TypeError {}

And if I expand the arrow next to it, it points me to the line where the console.error() call was made, so I don't get to see where the original error actually happened.

What would be the best way to include the original error information (including message and complete stack trace to the exact location where the error happened) in the console output?

urish
  • 8,943
  • 8
  • 54
  • 75

2 Answers2

9

Object Error has a property stack. Print it out.

console.error("Exception thrown", e.stack);

Please note that stack property is not standardized and it is only used by V8 based browsers + IE. Firefox uses different convention.

Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
  • 2
    It seems that Firefox now uses `stack` too: http://stackoverflow.com/questions/147891/javascript-exception-stack-trace – Nacho Coloma Aug 21 '16 at 04:59
7

You can output the error as object

console.error("%O", e)

enter image description here

Using string substitutions

Qwerty
  • 29,062
  • 22
  • 108
  • 136