bestiejs / json3

A JSON polyfill. No longer maintained.
https://bestiejs.github.io/json3
Other
1.02k stars 150 forks source link

SCRIPT5022: Exception thrown and not caught #87

Closed githubuser5859 closed 8 years ago

githubuser5859 commented 8 years ago

HTML page:

<!DOCTYPE html>
<html>
    <head>
        <title>JSON3 Test</title>

        <!-- JSON3 library (Development)
        <script type="text/javascript" src="/e2/js/json3_v3.3.2.js"></script>

        <!-- JSON3 library (Minified) (Production)
        <!-- Error occurs with minified file, as well -->
        <!--<script type="text/javascript" src="/e2/js/json3_v3.3.2.min.js"></script>-->

        <script type="text/javascript">

            // Purposely incorrect to cause exception 
            // Error: Reporting thrown exception not caught
            JSON.parse( "[1, 2, 3)" );

        </script type="text/javascript">

    </head>

    <body></body>
</html>

As you can see from the above sample HTML page, I purposely used an incorrect string to throw an exception. The exception is not getting caught. In fact, the error it produces the following in Microsoft IE7 through IE11:

SCRIPT5022: Exception thrown and not caught File: json3_v3.3.2.js, Line: 568, Column: 11

In Google Chrome, the following error appears and can be visible with the developer toolbar:

Uncaught SyntaxError: Unexpected token )

Now, my question is this: Is this by design or a bug? I can easily fix this by catching the exception, i.e. wrap the parse method with a try..catch block. But if I'm using a third-party plugin which relies on JSON parsing and it expects the JSON3 library to catch the exception, I may have to wait until the author fixes his/her plugin.

Another workaround, particularly for legacy versions of IE, is to employ the JSON2 library (https://github.com/douglascrockford/JSON-js). I did not experience any errors related to uncaught thrown exceptions with the JSON2 library. I didn't look at the code, but I gather it takes care of catching these exceptions.

So, again, is this uncaught exception by design and it's up to the developer to catch it or is it a bug and JSON3 should take care of catching exceptions?

Thank you very much.

bnjmnt4n commented 8 years ago

The exception is thrown due to invalid JSON syntax: [1, 2, 3). Since you did not wrap your JSON.parse usage in a try-catch block, the exception is not caught and bubbles up, which is the expected behaviour, as per the spec. If JSON 2 does not do so, it is an error on their part.