Missing exception info in NodeJS JSON.parse - json

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?

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.

Related

Extra character placed in path of DSC config - Azure PS

I'm trying to work out why I'm getting the error below; the path to the configuration.ps1 file should be configuration\configuration.ps1, however its failing as its reading it as configuration.0\configuration.ps1.
the whole error message is below, has anyone else come across this?
"status": "Failed",
"error": {
"code": "ResourceDeploymentFailure",
"message": "The resource operation completed with terminal provisioning state 'Failed'.",
"details": [
{
"code": "VMExtensionProvisioningError",
"message": "VM has reported a failure when processing extension 'CreateADPDC'. Error message: \"The DSC Extension received an incorrect input: An error occurred while
executing script or module 'configuration.ps1': The term 'C:\\Packages\\Plugins\\Microsoft.Powershell.DSC\\2.77.0.0\\bin\\..\\DSCWork\\configuration.0\\configuration.ps1' is not
recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again..\nPlease correct the input and retry executing the extension.\"."
}
]
}
}'
At line:4 char:14
+ ... New-AzureRmResourceGroupDeployment -Name "coredeployment1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureRmResourceGroupDeployment], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet
New-AzureRmResourceGroupDeployment : 18:31:08 - VM has reported a failure when processing extension 'CreateADPDC'. Error message: "The DSC Extension received an incorrect input: An
error occurred while executing script or module 'configuration.ps1': The term
'C:\Packages\Plugins\Microsoft.Powershell.DSC\2.77.0.0\bin\..\DSCWork\configuration.0\configuration.ps1' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again..
Please correct the input and retry executing the extension.".
Thanks in advance :)

sails-mysql error handling : TypeError: Converting circular structure to JSON

Server: Sailsjs
Database: mysql
Node Library used: sails-mysql(0.11.5)
I am trying to insert a data in mysql from sailsjs node server.
Data to be inserted:
{
"first_name": "Admin Testing",
"last_name": "User",
"email": "admin14#testing.com",
"role_id": 8
}
Where role_id is having a foreign key relation to model role.
Here the role_id : 8 doesn't have value in role table. So while inserting, it is throwing the error. But that error we couldn't console or json.stringify since the following error occurs:
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at /var/www/aitachatbot/server/api/controllers/UserController.js:38:42
at wrapper (/var/www/aitachatbot/server/node_modules/waterline/node_modules/lodash/index.js:3602:19)
at applyInOriginalCtx (/var/www/aitachatbot/server/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/var/www/aitachatbot/server/node_modules/waterline/lib/waterline/utils/normalize.js:331:16)
at error (/var/www/aitachatbot/server/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/var/www/aitachatbot/server/node_modules/switchback/lib/factory.js:56:28)
at /var/www/aitachatbot/server/node_modules/sails-hook-validation/lib/create.js:66:21
at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:223:14
at wrapper (/usr/local/lib/node_modules/sails/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:335:16)
at error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:56:28)
at afterwards (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/adapter/dql.js:87:16)
at wrapper (/usr/local/lib/node_modules/sails/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:335:16)
at error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:56:28)
at sendBackError (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/spawn.js:97:11)
at Object.poolfully [as releaseConnection] (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/release.js:28:12)
at /var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/spawn.js:90:37
at Query._callback (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/adapter.js:395:27)
at Query.Sequence.end (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Query.ErrorPacket (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)
at Protocol._parsePacket (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:280:23)
at Parser.write (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:73:12)
How can we handle this error in sailsjs?
In theory, you don't want these errors to ever show up in production... even if they did, the full json dump of the error object probably is not something a run-of-the-mill user wants to see.
You may also be asking about how to get full info out of this error while debugging. I guess the good news there is, you seem to already know the root cause of your error!
The error objects we have in node can have pretty different structures depending where they come from, but I have yet to encounter an error that does not have smart casting of the errors to strings. That means that even if console.log(err) fails, something like: console.log('Got an error: ' + err) will likely work, casting the error to a string.
The code could be something like this:
User.create({
"first_name": "Admin Testing",
"last_name": "User",
"email": "admin14#testing.com",
"role_id": 8
}).exec(function(err, createdUser) {
if (err) {
var readableErr = '' + err;
console.log('Error creating user: ' + readableErr);
// return something the client will recognize and interpret
// you can use http error codes, or your own conventions
return res.send({
success: false,
message: readableErr
});
}
// do something with createdUser...
});

npm unexpected token / in config.json at position 98

I have seen several unexpected token errors related to npm but this one is yet again unique to me. I could not find any similar issues posted by others. My config file just has connection objects to my local mongodb, rabbitmq "amqp", wordpress plugin and mysql DB.
Could anyone help me with this error in case they've seen it before?
C:\xampp\htdocs\livetrader\chat\node_modules\nconf\lib\nconf\stores\file.js:160
throw new Error("Error parsing your configuration file: [" + this.file + ']: ' + ex.message);
^
Error: Error parsing your configuration file:
[C:\xampp\htdocs\livetrader\chat/config.json]: Unexpected token / in JSON at position 98
Updating this post with the config.json file referenced in this error
{
"port": 1337,
"mongoose": {
"uri": "mongodb://localhost:27017/livetrader"
},
"amqp":{
"uri": "amqp://guest:guest#localhost:15672",
"queue": "TickData"
},
"sql":{
"host":"localhost",
"database":"db_main",
"user":"root",
"password":""
},
"wp":{
"host":"http://forextrader.dev",
"LOGGED_IN_KEY":"MY_LOGGED_IN_KEY",
"LOGGED_IN_SALT":"MY_LOGGED_IN_SALT",
"prefix":"wp_",
"avatarPath":"http://localhost/livetrader/wp-content/uploads/avatars",
"myCreedApi":"MY_API_KEY"
},
"guest":{
"cookie_name": "trading-forex-guest",
"ttl": 180
}
}
Updating the back-end config path
"use strict";
var nconf = require('nconf');
nconf.argv()
.env()
.file({
file: process.cwd() + '/config.json'
});
module.exports = nconf;
Your JSON file is property formatted. JSON.parse() takes it, no problem. Character 98 is not a slash, either.
There is, however, a suspicious slash in your path:
C:\xampp\htdocs\livetrader\chat/config.json
The final slash is unix-style, not windows-style. Could that be causing the problem?
If that's not it, you must be reading the wrong file, or passing it the wrong way to a function. Try using console.log to figure out what exactly is reaching JSON.parse().
Giving objects to JSON.parse() can cause unexpected errors, since .toString() is invoked. For example:
> JSON.parse({a:1})
SyntaxError: Unexpected token o in JSON at position 1
> ({a:1}).toString()
'[object Object]'
So, to recap, you must be:
Reading the wrong file
Passing an object that's not a String to JSON.parse()
Having a strange problem with the inverted slash in the path

log4js configure function error [NodeJs]

I am getting the following error in console window when running my NodeJs application. I am using log4js for logging. Runtime platform is express.
Error:
undefined:1
?{
^
SyntaxError: Unexpected token ? in JSON at position 0
Code:
var log4js = require('log4js');
var mylog = log4js.configure('log4jsConfig.json');
logger = log4js.getLogger("absolute-logger");
Config json:
{
"appenders": [
{
"type": "file",
"absolute": true,
"filename": "c:/temp/log_file.log",
"maxLogSize": 20480,
"backups": 10,
"category": "absolute-logger"
}
]
}
Question:
Any thoughts. I am thinking this is parsing error, but not sure how to resolve it.
Thanks,
Are you on a windows system? Sometimes, parsers get upset with \r\n (carriage returns). Try converting it UNIX (new line only) style lines.

JSON-RPC Message error when starting geth node or testrpc

I am trying to create a private network so that I can start testing my Solidity code. However, when starting the a geth private network with geth --rpc but I then run into an error for an invalid response. {"jsonrpc":"2.0","error":{"code":-32600,"message":"EOF"}} when checking localhost:8545.
I don't think it matters, but my genesis.json file is
{
"nonce": "0x0000000000000042", "timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x0", "gasLimit": "0x8000000", "difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333", "alloc": { }}
I have also tried creating a test network with testrpc with just the command testrpc but here the localhost:8545 returns a parsing error {"jsonrpc": "2.0", "id": null, "error": {"message": "Parse error", "code": -32700}}.
What is the JSON that I am sending because it seems to be incorrectly written?
Thanks
It's hard to tell what exactly you are trying, but the JSON RPC endpoint of geth requires a JSON command, for instance try to query the web3 version with the following request:
{
"method": "web3_clientVersion",
"params": []
}
It complains because you do not provide any request, i.e., running a plain testrpc command.
But inbetween the lines I read that you are testing your solidity code. Have you had a look at the wonderful browser solidity?