在NodeJS中,如果我让JSON.parse异常无法处理并随后使服务器崩溃,我会将一些重要信息输出到控制台。
我的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"
}
}
]
}
当我让它无法处理时,这是控制台输出:
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)
但是如果我抓住异常来防止崩溃,那就像这样记录......
try{
var fileData = JSON.parse(fileText);
}
catch (ex) {
console.log("REASON FOR JSON FAILURE: " + ex, ex.arguments, ex.stack.split("\n"));
}
我得到这样的输出:
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)' ]
错过了崩溃日志中包含错误文本的行号和剪辑的关键有用信息:
undefined:12
this should make it blow up
^
我如何才能达到这一点,以便将其包含在我的错误消息中?
答案 0 :(得分:1)
您无法获得从错误中显示的第一位,因为它不是错误的一部分。
undefined:12
this should make it blow up
^
这是因为节点在死亡之前添加该部分以显示它死亡的原因,然后显示JSON.parse生成的错误。
要获得更详细的消息,您必须使用JSON.parse之外的其他内容。正如robertklep所提到的,如果你在JSON解析上获得更多细节很重要,你可以尝试greatjson或类似的东西,例如你正在构建一个解析JSON并返回错误的服务。