开发者

Can syntax errors be caught in JavaScript?

开发者 https://www.devze.com 2023-03-05 14:42 出处:网络
MDN states: A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.

MDN states:

A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.

But if there's a开发者_JAVA技巧 syntax error, how could the program even run in the first place?

How can JavaScript syntax errors even be caught?


You cannot use try-catch blocks to handle syntax errors as they are thrown while the code is being parsed and not while it's running.

However you can use window.onerror and figure out that there's an error. You must ensure that the onerror function is defined in a separate script tag and not in the tag in which the error may be present!

Eg:

This will not work, because the script is yet to start running when the error is thrown:

<script>
  window.onerror = function (e) {
    console.log('Error: ', e);
  };
  console.log('a'');
</script>

This will work:

<script>
  window.onerror = function (e) {
    console.log('Error: ', e);
  };
</script>
<script>
  console.log('a'');
</script>

jsfiddle demo


In the JS world, SyntaxError CAN be a runtime exception. This can arise, for instance, when trying to parse a JSON response that isn't JSON format. The server can send back lots of types of responses, so if you send a HTML body response to your request that's expecting JSON in the body, you're going to get a SyntaxError thrown in the JS. In such a case, you would get an error message that looks something like this: SyntaxError: JSON Parse error: Unrecognized token '<'.

But there are other runtime SyntaxErrors you could get as well. Mozilla has a list of some here: SyntaxErrors for JSON parsing

You may want to catch these in your code. You can do so with a generic try/catch block like this:

try {
  JSON.parse('<html></html>');
} catch (e) {
  console.log("I catch & handle all errors the same way.");
}

OR you can look for the SyntaxError specifically:

try {
  JSON.parse('<html></html>');
} catch (e) {
  if (e instanceof SyntaxError) {
    console.log("I caught a pesky SyntaxError! I'll handle it specifically here.");
  } else {
    console.log("I caught an error, but it wasn't a SyntaxError. I handle all non-SyntaxErrors here.");
  }
}

Mozilla has even more info on JS errors and handling them.


It's runtime errors that can be caught with try-catch, not syntax errors (if you eval your code you can handle syntax errors in the evaled code but that's just weird).

I'd recommend you read these:

  • https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#try...catch_Statement

  • https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#Exception_Handling_Statements


You can catch programmer-generated and runtime exceptions but you cannot catch JavaScript syntax errors, though you may handle them in some browsers using window.onerror.

This is taken from the book JavaScript- The Complete Reference by Thomas-Powell which I like very much. You can refer to the code examples in that book.


You specifically cannot catch parser-generated SyntaxErrors since they are thrown by the parser, which has no idea what try/catch blocks do. More info on that - Learning how programming languages work

There is a way to catch SyntaxErrors that are generated during code execution. This method is slow, and I would not recommend it. You can catch SyntaxErrors using eval().

var code = `function() {
doSomething()
somethingElse()
var x = 5 + 5
// No ending curly brace` // The code to be run using eval

try {
  eval(code) // Try evaluating the code
} catch (e) {
  if (e.name !== 'SyntaxError') throw e // Throw the error if it is not a SyntaxError
  
  console.log('A SyntaxError has been caught\n\nDetails:\n' + e) // It is a SyntaxError
}

Alternatively, you could use new Function(), which is up to 93% faster - https://jsben.ch/1HLQ1

var code = `function() {
doSomething()
somethingElse()
var x = 5 + 5
// No ending curly brace` // The code to be run using eval

try {
  new Function([], code) // Try evaluating the code
} catch (e) {
  if (e.name !== 'SyntaxError') throw e // Throw the error if it is not a SyntaxError
  
  console.log('A SyntaxError has been caught\n\nDetails:\n' + e) // It is a SyntaxError
}

0

精彩评论

暂无评论...
验证码 换一张
取 消