3

I have been battling this issue for half a week to no avail, my problem is:

using Node.js 0.10.12 to parse JSON files like so:

var invalidJson = '{ this is bad }';



try {
    JSON.parse( invalidJson );
}

catch (exc) {
    console.log(exc.stack);
    throw exc;
}

the output:

SyntaxError: Unexpected token t
    at Object.parse (native)
    at Object.<anonymous> (test.js:7:10)
    ...
    at node.js:901:3

test.js:12
    throw exc;

..And then a duplicate of 'SyntaxError: Unexpected token t..' because I re-throw the exception

Now, when doing:

JSON.parse( invalidJson );

without try {} catch {}

I get this error:

undefined:1
{ this is bad }
  ^
SyntaxError: Unexpected token t
    at Object.parse (native)
    at Object.<anonymous> (test.js:17:6)
    ...
    at node.js:901:3

this error message tells me exactly where the JSON parsing broke. When the JSON file is large, it's virtually impossible to locate the error without these details.

How can I forward this descriptive error message in my custom try{}catch{} exception handler?

thanks!

4

1 回答 1

1

Well even with:

$ node --builtins-in-stack-traces test.js

And test.js:

var invalidJson = '{ this is bad }';

//Make err.stack return an array of CallSite objects instead of string
Error.prepareStackTrace = function(_, stack) {
    return stack;
};


try {
    JSON.parse( invalidJson );
}

catch (exc) {
    var asd = exc.stack;
}

asd.forEach( function(v){
    console.log((v.getMethodName() || v.getFunctionName()) +
         ":" + v.getLineNumber());
});

The output is:

MakeGenericError:118
MakeSyntaxError:324
parse:56
null:9
_compile:456
.js:474
load:356
_load:312
runMain:497
startup:119

Doesn't seem possible from Javascript, you should file a bug to expose the JSON line number information to JS since they are obviously accessing it when doing the ^--- thing. JSON should not be hand written so syntax errors shouldn't be common unless the JSON serializer being used is somehow broken.

于 2013-08-05T15:06:43.650 回答