phil294
phil294

Reputation: 10852

JSON.parse("") fails with script error but not inside try/catch

On Chrome (not on Firefox though),

JSON.parse("")

fails with "Script error." You can reproduce it by running the script above or by running https://jsfiddle.net/xupf27nh/1/. Why the script error? There is no cors activity here...?

try {
    JSON.parse("")
} catch(e) {
    throw e;
}

correctly prints the error message "message": "Uncaught SyntaxError: Unexpected end of JSON input",. Why is it different this time? And why doesnt

a.b.c.d.e.f()

fail with script error but correctly displays the error message?

Upvotes: 3

Views: 545

Answers (1)

Jean Bouvattier
Jean Bouvattier

Reputation: 365

Browsers intentionally hide errors originating from script files from different origins for security reasons. In this case, because of CORS setup, the error returned by JSON.parse is treated as a different origin and therefore hidden by your browser.

However when you encapsulate with try\catch, the error is thrown by your code :

try {
    JSON.parse("")
} catch(e) {
    // your browser see an error thrown from here : your code
    throw e;
}

Therefore your chrome browser does not identify the error from another origin, this is the same reason a.b.c.d.e.f() error is correctly displayed : it is identified as an error thrown by your code.

Note that browsers have different specifications and implementations (and bugs) of CORS policy so they may behave differently like here.

You can learn more about this specific script error here : https://blog.sentry.io/2016/05/17/what-is-script-error

Upvotes: 5

Related Questions