Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting stack trace for an error when running code from the console in Chrome

I am calling a function from the console but when it throws an exception I do not receive a stack trace like I would if the code was executed normally.

Is there a way I can modify my command (perhaps with try/catch) to have it provide me this information?

to clarify:

page.js:

function otherStuff() { return ['a','b',undefined,'c'];
function doStuff() {
    var x = otherStuff();
    var z = parseInt(x[2]); // this will throw an error
}

console, after loading a html page that links page.js

> otherStuff();

I get no line number from the Error that is returned to me. When running it from the page (instead of the console) i would receive a line number and a stack trace.

like image 390
Steven Lu Avatar asked Oct 18 '11 19:10

Steven Lu


2 Answers

Although verbose, this will print the stack trace of an interactive error in the Chrome JS console:

try { 
    throw new Error(); 
} catch (e) { 
    console.error(e.stack); 
}

Unfortunately this won't work if a non-Error object is thrown.

like image 91
millimoose Avatar answered Nov 15 '22 08:11

millimoose


You have an error in your code.

You are missing a closing brace:

function otherStuff() { return ['a','b',undefined,'c']; //} where am i?
function doStuff() {
    var x = otherStuff();
    var z = parseInt(x[2]); // this will throw an error
}

Side point:

parseInt(undefined) does not throw an error. case in point: http://jsfiddle.net/maniator/Zequj/2/

like image 30
Naftali Avatar answered Nov 15 '22 07:11

Naftali