79221550

Date: 2024-11-25 03:30:07
Score: 1
Natty:
Report link

Errors like that are not quite runtime exceptions, there are lexical ones. The exception is thrown not by execution of an ill-formed code, but by loading the code text and parsing it. You can handle them, but you don't have the context to do so.

You can get the context if you dynamically load a script text. For example, you can do it with a Web page. You can dynamically insert a script in HTML. Catching syntax errors in a dynamically loaded script is possible, but pretty complicated, I would need to show a good deal of code. You can try to use this idea, if you like it, ask more questions if you face problems.

By the way, you cannot do such tricks with module importing.

// You cannot to it!
try {
    // unfortunately it won't work: SyntaxError
    import LoginPage from "./LoginPage.mjs";
    // import only works in the most outer scope
} catch (e) {
    console.log(e);
}

Another option is the Function constructor. You can take some code text, arguments, pass them to the Function constructor and execute that code. Consider this a safe and more flexible variant of eval. Note that eval is considered risky and should be avoided. At the same time, there are cases where the Function constructor is absolutely necessary. However, many people find this topic very controversial and may down-vote my answer fiercely. 😏

Now, you can wrap a Function constructor call in try-catch.

Let's see:

const badCode = `
    ? some garbage
    return a + b;
`;

try {
    const result = new Function("a", "b", badCode)(2, 3);
    console.log(`Function return: ${result}`);
} catch(e) {
    console.error(`Event SyntaxError can be caught: ${e.message}`);
}

console.log("In all cases, execution recovers");

Comment out ?? garbage to run this dynamic code:

const badCode = `
    //? some garbage
    return a + b;
`;

try {
    const result = new Function("a", "b", badCode)(2, 3);
    console.log(`Function return: ${result}`);
} catch(e) {
    console.error(`Event SyntaxError can be caught: ${e.message}`);
}

console.log("In all cases, execution recovers");

Reasons:
  • RegEx Blacklisted phrase (2): down-vote
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Sergey A Kryukov