JavaScript Eval:如果出现错误,在控制台中显示正确的脚本参考链接

问题描述 投票:0回答:1

如果我评估故意犯错误的脚本,我会在控制台中收到错误日志,并在右侧显示脚本参考链接。例如,这是脚本:

my_script = 'const a = 2;\nconst b = a 2;';

eval(my_script)

这是执行后的控制台截图:

console after execution

在右上角,您可以看到这个可爱的脚本参考链接,我非常喜欢和欣赏。欣赏的主要原因是,通过点击它我可以查看导致错误的脚本,甚至可以查看发生错误的确切位置:

debugger after execution

但是,如果我想在错误时发生一些额外的逻辑,因此我添加带有此逻辑的 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)
}

这是我执行后看到的: console after second execution

如您所见,跟踪仅包含 2 条记录 - 初始代码和 eval 代码,但第一个记录不可点击。这是我单击唯一可用的脚本参考链接后看到的内容: debugger after second execution, lost initial script reference

调试器现在向我显示评估代码本身,而不是正在评估的初始脚本

   

在 try/catch 语句中评估任意脚本时如何保留脚本引用?有没有办法捕获 eval 错误并仍然能够在 chrome 调试器中查看实际脚本?

javascript google-chrome google-chrome-devtools eval
1个回答
0
投票

我不知道为什么会这样,但是在捕获末尾使用

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;
    })
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.