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

心不动则不痛 提交于 2019-12-04 22:49:27

问题


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.


回答1:


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.




回答2:


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/



来源:https://stackoverflow.com/questions/7812682/getting-stack-trace-for-an-error-when-running-code-from-the-console-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!