如果我评估故意犯错误的脚本,我会在控制台中收到错误日志,并在右侧显示脚本参考链接。例如,这是脚本:
my_script = 'const a = 2;\nconst b = a 2;';
eval(my_script)
这是执行后的控制台截图:
在右上角,您可以看到这个可爱的脚本参考链接,我非常喜欢和欣赏。欣赏的主要原因是,通过点击它我可以查看导致错误的脚本,甚至可以查看发生错误的确切位置:
但是,如果我想在错误时发生一些额外的逻辑,因此我添加带有此逻辑的 try/catch 语句,我会丢失脚本引用,并且我可爱的脚本引用链接不再指向我的初始脚本。相反,它会导致 eval 代码本身。这是新脚本:
my_script = 'const a = 2;\nconst b = a 2;';
try {
eval(my_script)
} catch (e) {
// first we do some additional logic like error type checking and etc
// then we just log error so a user could view the erroneous script, the exact position of error and maybe make amends
console.error(e)
}
如您所见,跟踪仅包含 2 条记录 - 初始代码和 eval 代码,但第一个记录不可点击。这是我单击唯一可用的脚本参考链接后看到的内容:
调试器现在向我显示评估代码本身,而不是正在评估的初始脚本
在 try/catch 语句中评估任意脚本时如何保留脚本引用?有没有办法捕获 eval 错误并仍然能够在 chrome 调试器中查看实际脚本?
我不知道为什么会这样,但是在捕获末尾使用
Promise
和 throw
可以提供您想要的参考:
my_script = 'const a = 2;\nconst b = a 2;';
new Promise(() => eval(my_script))
.catch((e) => {
console.log("do something when error");
// first we do some additional logic like error type checking and etc
// then we just log error so a user could view the erroneous script, the exact position of error and maybe make amends
console.error(e);
throw e;
})