Search code examples
javascripttry-catcheval

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


I have the following code to run in an 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;). However, instead of the catch block firing, an exception is thrown as if there is no try/catch block. But, if I were to run eval("asd()"), the catch block would catch the error and return a string. 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.


Solution

  • You need to handle eval as a promise since you are using a promise inside it.

    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).

    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!