while running below code
const newman = require("newman");
newman.run(
{
collection: require("./test.postman_collection.JSON"),
reporters: "cli",
},
function (err) {
if (err) {
throw err;
}
console.log("collection run complete");
}
);
though the collection is in proper json format still its throwing below error.
test.postman_collection.JSON:2
"info": {
^
SyntaxError: Unexpected token ':'
In my case, the file was without extesion (.json). Adding the extension solved the error
Related
I have a nuxt app with express and mySQL.
Problem : I am unable to display the express res.send() custom error message on the vue side
Let's pretend I want to display infos of one single user.
Here is my back-end code :
// Find a single User with a userId
exports.findOne = (req, res) => {
User.findById(req.params.userId, (err, data) => {
if (err) {
if (err.kind === 'not_found') {
res.status(404).send({
message: `Not found User with id ${req.params.userId}.`
})
} else {
res.status(500).send({
message: 'Error retrieving User with id ' + req.params.userId
})
}
} else { res.send(data) }
})
}
And here is the Vue part
<script>
import axios from 'axios'
import appNavbar from '~/components/appNavbar.vue'
export default {
components: {
appNavbar
},
data () {
return {
userId: '',
userData: '',
errorMsg: ''
}
},
methods: {
fetchUser (evt) {
evt.preventDefault()
return axios.get('/api/users/' + this.userId)
.then((res) => {
this.userData = res.data
})
.catch((err) => {
this.errorMsg = err.toJSON()
})
}
}
}
</script>
When I give the id of a non-existing user, I want to be able to get the custom error message written in the back, and display it in the front
BUT I only get this JSON
{ "message": "Request failed with status code 404", "name": "Error" }
Does anyone have a clue ?
Thanks !
This error maybe occours because you are not setting the host when you call teh API at line:
return axios.get('/api/users/' + this.userId)
404 error is because browser not found this endpoint.
In this case, I recommend you try to call this endpoint in another tool (like Postman) and certify if your API is responding correctly.
After that, fix your call to endpoint, maybe it will be somwthing like the code bellow and try again:
return axios.get(`${your host here}/api/users/ + ${this.userId}`)
EDIT : SOLUTION FOUND
Answer found here: https://github.com/axios/axios/issues/960#issuecomment-309287911
On the vue part, the catch should return err.response, and not just err.
So in order to display your custom error message, it should be like this:
.catch((err) => {
this.errorMsg = err.response
I have a json file which is updated every 30 seconds by an application on the server. I have written a small server script for nodejs to provide this json file over websocket (socket.io) as given below.
var app = require('http').createServer();
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8081, '127.0.0.1');
io.on('connection', function(socket) {
fs.readFile('/tmp/live-info', 'utf8', function (err, data) {
if (err) throw err;
firstDataObj = JSON.parse(data);
socket.emit('alert', firstDataObj );
});
});
var prObj;
setInterval(function(){
fs.readFile('/tmp/live-info', 'utf8', function (err, data) {
if (err) throw err;
data = JSON.parse(data);
scTime = data.schedulerTime;
delete data.schedulerTime;
if (JSON.stringify(prObj) !== JSON.stringify(data)) {
prObj = data;
console.log(prObj.current.name, io.engine.clientsCount);
prObj.schedulerTime = scTime;
io.emit('alert', prObj );
delete prObj.schedulerTime;
} else {
console.log("No change", prObj.current.name, "Total connections: ", io.engine.clientsCount);
}
});
}, 21100);
As you can see, the script periodically checks for changes to the json file and will emit the parsed object if changes in contents (except the timestamp) are detected.
I am managing nodejs process on the server using pm2. Everything works fine but I am repeatedly getting the follow error on the logs
SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at /var/www/scheduleio/server.js:15:25
at tryToString (fs.js:449:3)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:436:12)
There are no noticeable breaks found on the client as well. However, I would like to understand how to fix this error as I am getting around 200 of them on the logs each day and if the script can be enhanced in any way (as this is my first such script).
My guess is the error comes when the file is being written by the other application while your nodejs script is checking it therefore parsing the JSON while it's not completely written.
The error unexpected end of JSON input means the JSON is malformed.
For some reason I am getting the Process exited before completing request error.
Here is my code:
var http = require('http');
var aws = require('aws-sdk');
var ddb = new aws.DynamoDB();
function getUser(userid) {
var q = ddb.getItem({
TableName: "clients",
Key: {
ClientID: { S: userid } }
}, function(err, data) {
if (err) {
console.log(err);
return err;
}
else {
console.log(data);
}
});
//console.log(q);
}
exports.handler = function(event, context) {
getUser('user23');
console.log("called DynamoDB");
};
After googling a few people suggested changing the time out to a higher amount. Which I did to one minute.
However the function only took:
Duration : 2542.23 ms
I have also checked and double checked the table name and the key name etc...
The console log has this :
2016-03-21T04:09:46.390Z - Received event
2016-03-21T04:09:46.751Z - called DynamoDB
2016-03-21T04:09:47.012Z - {}
END RequestId: id123
Can anyone see why this is not working?
Edit
As per the answer below I tried:
console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
dynamodb.listTables(function(err, data) {
console.log(JSON.stringify(data, null, ' '));
});
var tableName = "clients";
var datetime = new Date().getTime().toString();
dynamodb.getItem({
TableName: tableName,
Key: {
ClientID: { S: "gr5f4sgnca25hki" } }
}, function(err, data) {
if (err) {
context.done('error','putting item into dynamodb failed: '+err);
}
else {
context.done(data);
}
});
};
but now my response is:
"errorMessage": "[object Object]"
What I am trying to do is this: Check if Item exists in database. Get the parameters from the entry if exists, then do something with the parameters
Can anyone help me?
First of all, context.done expects an Error object as the first argument, not a string containing the word "error".
Second, if the Error object is null or undefined, then the termination will be taken as a succeed.
Now, consider your callback function:
function (err, data)
{
if (err) {
context.done('error', 'putting item into dynamodb failed: ' + err);
}
else {
context.done(data);
}
}
If you have an error, then your lambda will terminate in a failure, which is expected, but the errorMessage you'll get would simply be "error", which isn't much informative.
If you don't have an error, then your lambda will also terminate in a failure, because you are passing in data as the first argument to context.done, and remember that the first argument is always the Error object.
To fix this, you can simply do:
function (err, data)
{
if (err) {
context.done(err);
} else {
context.done(null, data);
}
}
Or even better:
function (err, data)
{
context.done(err, data);
}
If you don't want to handle the item and just return it immediately, you can use context.done as your callback function to the DynamoDB operation:
dynamodb.getItem({
TableName: tableName,
Key: {
ClientID: { S: "gr5f4sgnca25hki" }
}
}, context.done);
You need to signal Lambda end of function.
Important
To properly terminate your Lambda function execution, you must call context.succeed(), context.fail(), or context.done() method. If you don't, either your Lambda function will continue to run until the Node.js event queue is empty, or your Lambda function times out.
Here is an example:
https://gist.github.com/markusklems/1e7218d76d7583f1f7b3
"errorMessage": "[object Object]"
can be solved by a small change as follows
function(err, data) {
if (err) {
context.done(err);
}
else {
context.succeed(data);
}
});
Note where context.succeed differs() from context.done()
I have a file moving utility on server side,
if the target directory does not exist, the error returned is (over the wire):
{errno: -2,
code: 'ENOENT',
path: 'uploads/workgroup/message.docx'}
The piece of code on the server side:
fs.rename(oldpath,newpath, function(err) {
if(err) {
err.message = 'Target directory does not exist.';
return res.send(400, err);
}
As you see, the err.message is ignored.
If I create a new error object, everything is fine:
fs.rename(oldpath,newpath, function(err) {
if(err) {
err.message = 'Target directory does not exist.';
var err2 = new Error();
err2.message = err.message;
err2.code = err.code;
err2.path = err.path;
err2.errno = err.errno;
return res.send(400, err2);
}
I have no idea, why the original error object can not be modified.
I tried console.log(util.inspect(err, {showHidden: true, depth: null}));, but it did not give much clue.
Any explanation is much appreciated!
When an error object is created with an argument passed to the constructor as in:
var e = new Error("Some Message Here");
it creates an Error object that has a .message property that is not enumerable. And, JSON.stringify() which res.send() uses does not include enumerable properties. And, it stays non-enumerable even when you assign a different value to that property.
But, if you create the Error object without a message passed to the constructor and then assign the .message property to it like this:
var e = new Error();
e.message = "Some Message Here";
Then, the .message property ends up as enumerable and will be included in JSON.stringify(). I have no idea why the V8 engine does it this way, but it does.
The enumerability of the property is configurable, so you could change it which would make it so res.send() would include it:
fs.rename(oldpath,newpath, function(err) {
if(err) {
Object.defineProperty(err, "message", {enumerable: true});
err.message = 'Target directory does not exist.';
return res.send(400, err);
}
Or, you could just use your own property name which will be enumerable by default:
fs.rename(oldpath,newpath, function(err) {
if(err) {
err.reason = 'Target directory does not exist.';
return res.send(400, err);
}
When validating a mongoose schema in 'pre' of parallel middleware
schema.pre('save', true, function (next, done) {
if(...) {
next(new Error('Some error message'));
}
next();
});
I return an error and it is available in the callback function:
model.save({},{}, function(err) {
res.json(400, err);
console.log(err)// I see in the console: [Error: 'Some error message']
})
But when I do
res.json(400, err);
I get an empty response
{} No properties
What is the reason for this?
JSON can't stringify errors. You'll need to use something else to send the error.
Perhaps just res.send(err.message), or something similar.