简体   繁体   English

JavaScript-eval中的嵌套函数不适用于try / catch块

[英]JavaScript - Nested functions in eval not working with try/catch block

I have the following code to run in an eval() : 我有以下代码在eval()运行:

const code = `
    async function func() {
        asd();
    }

    func();
`;

try {
    console.log("running code");
    return eval(code);
}
catch (err) {
    console.log("error");
    return err.message;
}

In this case, asd is undefined , and so I would expect a reference error to be returned as a string ( return err.message; ). 在这种情况下, asdundefined ,因此我希望将引用错误作为字符串return err.message;return err.message; )。 However, instead of the catch block firing, an exception is thrown as if there is no try/catch block. 但是,不是触发catch块,而是抛出异常,就像没有try / catch块一样。 But, if I were to run eval("asd()") , the catch block would catch the error and return a string. 但是,如果我要运行eval("asd()")catch块将捕获错误并返回一个字符串。 Is there something different I need to do for nested functions? 嵌套函数需要做些不同的事情吗?

Note: This entire code is in an async function due to other code (before const code ... ), if that makes a difference. 注意:整个代码由于其他代码(在const code ...之前)而处于异步函数中,如果有区别的话。

You need to handle eval as a promise since you are using a promise inside it. 您需要将eval处理为一个承诺,因为您在其中使用了一个promise。

 const asyncEval = () => { const code = ` async function func() { asd(); } func(); `; console.log("running code"); return Promise.resolve(eval(code)); } const ele = document.getElementById('result'); asyncEval() .then(res => { ele.innerText = res; }) .catch(err => { ele.innerText = "ERROR: " + err; }) 
 <pre id="result"></pre> 

To ensure it works if there is a promise returned or not you can do Promise.resolve(eval(code)) instead of eval(code) . 为了确保无论是否返回承诺都可以使用它,您可以执行Promise.resolve(eval(code))而不是eval(code)

Either way, I would also recommend reading this and not using eval: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval ! 无论哪种方式,我都建议您阅读本指南,而不要使用eval: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM