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!

1
  • Unfortunatly I haven't found any solution yet, but someone did. I'm using this online tool to check JSON errors jsoneditoronline.org Commented Apr 28, 2016 at 15:55

1 Answer 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.

Sign up to request clarification or add additional context in comments.

2 Comments

"JSON should not be hand written". Really? What's an option for writing config files?
@RafaelVega I think the point is that JSON is very verbose and prone to syntax errors. While something like YAML is less verbose, more readable, a subset of JSON and the js-yaml will give descriptive syntax issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.