Doug
Doug

Reputation: 642

Missing exception info in NodeJS JSON.parse

In NodeJS, if I let a JSON.parse exception go unhandled and subsequently crash the server, I get an important bit of information outputted to the console.

My JSON:

{
    "familyName": "The Flintstones",
    "familyContact": {
        "fullName": "Wifie Flintstone",
        "contact": {
            "street1": "1 Granite Ave",
            "city": "Bedrock",
            "state": "TX",
            "postal": "10000"
        }
    },
    this should make it blow up
    "patients": [{
        "personInfo": {
            "fullName": "Wilma Flintstone"
        }}, {
            "personInfo": {
                "fullName": "Fred Flintstone"
            }
        }
    ]
}

This is the console output when I let it go unhandled:

undefined:12
    this should make it blow up
    ^
SyntaxError: Unexpected token t
    at Object.parse (native)
    at Object.exports.uploadPackage.flowUploads.post.flowUploads.write.onDone (/home/ubuntu/workspace/app/controllers/admin/admin.families.server.controller.js:99:27)
    at module.exports.$.write.pipeChunk (/home/ubuntu/workspace/app/services/flowUploads.js:173:49)
    at Object.cb [as oncomplete] (fs.js:169:19)

but if I catch the exception to prevent the crash, and log like so...

try{
    var fileData = JSON.parse(fileText);
}
catch (ex) {
    console.log("REASON FOR JSON FAILURE: " + ex, ex.arguments, ex.stack.split("\n"));
}

I get output like this:

REASON FOR JSON FAILURE: SyntaxError: Unexpected token t [ 't' ] [ 'SyntaxError: Unexpected token t',
  '    at Object.parse (native)',
  '    at Object.exports.uploadPackage.flowUploads.post.flowUploads.write.onDone (/home/ubuntu/workspace/app/controllers/admin/admin.families.server.controller.js:100:27)',
  '    at module.exports.$.write.pipeChunk (/home/ubuntu/workspace/app/services/flowUploads.js:173:49)',
  '    at Object.cb [as oncomplete] (fs.js:169:19)' ]

Missing that key piece of useful info from the crash log that contains the line number and snip of faulty text:

undefined:12
    this should make it blow up
    ^

How I can get to that bit so I can include it in my error messaging?

Upvotes: 1

Views: 202

Answers (1)

Jedediah Smith
Jedediah Smith

Reputation: 578

You can't get that first bit you displayed from the error since it isn't part of the error.

undefined:12
this should make it blow up
^

This is because node is adding that section before dying to show why it died and then shows the error generated by JSON.parse.

To get more detailed messaging you will have to use something other then JSON.parse. As robertklep mentioned you could try greatjson or something similar if getting greater detail on your JSON parsing is important, such as if you are building a service which parses JSON and returns the errors.

Upvotes: 1

Related Questions