I want to update a field in the 'NotesDB' that indicates the number of comments on a specific Note. Parse Cloudcode should do this automatically after saving a comment.
In practice it sometimes does and it sometimes doesn't (even with the same user, on the same note). The comment itself is always saved properly.
Is there any way i can improve this code..?
Parse.Cloud.afterSave("CommentsDB", function(request) {
var OriginalNote = request.object.get("OriginalPostId");
var query = new Parse.Query("NoteDB");
query.get(OriginalNote, {
success: function(post) {
post.increment("NumberOfComments");
post.save();
},
error: function(error) {
console.log("An error occured :(");
}
});
As you code stands, it is not possible to see if the post.save() call is failing or not (and if it is, why), maybe try chaining your promises :
query.get(OriginalNote,{useMasterKey:true}).then (function (post) {
post.increment("NumberOfComments");
return post.save(null,{useMasterKey:true});
}).then (function (savedPost) {
console.log('post incremented ok to ' + savedPost.get('NumberOfComments'));
},function (err) {
//this function will catch any error in the promise chain : query.get() or post.save()
console.error('An error occured : ' + err.message);
});
Related
I've had this problem for almost a day and I don't know what else to do to solve it.
Dialogflow Fulfillment in Dialogflow ES just doesn't want to make any HTTP calls at all. I'm always getting this error: No responses defined for platform: DIALOGFLOW_CONSOLE
My entired code is below. The function that crash everything is:
function simpleGet(requestUrl) {
axios.get(https://eo1lbzchsaeazi9.m.pipedream.net/)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
function simpleGet(requestUrl) {
axios.get(https://eo1lbzchsaeazi9.m.pipedream.net/)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
sorry, there is some context missing here.
do you see the error message when trying to use fullfilments (ie. one API call to get on a backend an answer to a customer interaction?
Also, another clarifying question - is it Dialogflow ES or CX?
I've seen some developers struggling with this error and some of them fixed it by updating the package for fulfillments as described here: https://github.com/dialogflow/dialogflow-fulfillment-nodejs/issues/322
I can create 4 error scenarios when calling http.get(url, cb):
httpThrows()
Can be triggered with a wrong format of the url, or wrong callback, etc.
function httpThrows() {
try {
http.get("www.missing-protocol.com", res => {
console.log(res.statusCode);
});
} catch (error) {
console.log("http.get() throws an error.");
}
}
requestError()
It the main error handler and triggers on some network related issue, e.g. DNS lookup failed or server not responding, etc.
function requestError() {
var req = http.get("http://some-url-that-does-not-exist.com", res => {
console.log(res.statusCode);
});
req.on("error", err => {
console.log("req.on('error') called with error");
});
}
errorCode()
Server responded normally so no network errors (can handle server errors).
function errorCode() {
http.get("http://httpstat.us/501", res => {
console.log("Got error code:", res.statusCode);
});
}
responseError() (the problem)
An http.IncomingMessage is given in the callback as response or res. According to the documentation it is a Readable steam and that steam can emit an error event.
function responseError() {
http.get("http://some-ulr-with-error-halfway-through.com/", res => {
console.log(res.statusCode);
// This will never be emitted?
res.on("error", err => {
console.log("res.on('error') called with error", err);
});
});
}
So this last handler:
Is this event ever triggered when using http.request or http.get?
If so what can trigger the event?
For my understanding the only way to end up with an error in that case is if there would be an issue with Node or the Engine and in both cases you can't do much about it.
In this situations I prefer not to handle those cases because you have less code to review and maintain.
I'm trying to use the promise-circuitbreaker node module.
I am able to pass a parameter to the called function, however, I am unable to have the called function return a value back.
Furthermore, I keep getting a timeout which I don't understand. I am obviously missing something, however I can't find any solution in the docs (http://pablolb.github.io/promise-circuitbreaker/)
I've made a very simple sample app to show my difficulties:
var CircuitBreaker = require('promise-circuitbreaker');
var TimeoutError = CircuitBreaker.TimeoutError;
var OpenCircuitError = CircuitBreaker.OpenCircuitError;
function testFcn(input, err) {
console.log('Received param: ', input);
//err('This is an error callback');
return 'Value to return';
}
var cb = new CircuitBreaker(testFcn);
var circuitBreakerPromise = cb.exec('This param is passed to the function');
circuitBreakerPromise.then(function (response) {
console.log('Never reach here:', response);
})
.catch(TimeoutError, function (error) {
console.log('Handle timeout here: ', error);
})
.catch(OpenCircuitError, function (error) {
console.log('Handle open circuit error here');
})
.catch(function (error) {
console.log('Handle any error here:', error);
})
.finally(function () {
console.log('Finally always called');
cb.stopEvents();
});
The output I get from this is:
Received param: This param is passed to the function
Handle timeout here: { [TimeoutError: Timed out after 3000 ms] name: 'TimeoutError', message: 'Timed out after 3000 ms' }
Finally always called
In my case, I want a simple string to be returned. I don't want a timeout error.
If I uncomment the line //err('This is an error callback') in testFcn(), I get the following output:
Received param: This param is passed to the function
Handle any error here: This is an error callback
Finally always called
So it appears that the 2nd parameter in the called function is for error handling.
Any help would be greatly appreciated.
I am writing an updated testing library for Node.js and am trying to properly trap errors that occur in test callbacks
for some reason, the following code doesn't trap an AssertionError:
process.on('uncaughtException',function(err){
console.error(err); //an instance of AssertionError will show up here
});
[file1,file2,file2].forEach(function (file) {
self.it('[test] ' + path.basename(file), {
parallel:true
},function testCallback(done) {
var jsonDataForEnrichment = require(file);
request({
url: serverEndpoint,
json: true,
body: jsonDataForEnrichment,
method: 'POST'
}, function (error, response, body) {
if (error) {
done(error);
}
else {
assert(response.statusCode == 201, "Error: Response Code"); //this throws an error, which is OK of course
done();
}
});
});
});
I handle the callback (I named it "testCallback" above), with this code:
try {
if (!inDebugMode) {
var err = new Error('timed out - ' + test.cb);
var timer = setTimeout(function () {
test.timedOut = true;
cb(err);
}, 5000);
}
test.cb.apply({
data: test.data,
desc: test.desc,
testId: test.testId
}, [function (err) { //this anonymous function is passed as the done functon
cb(err);
}]);
}
catch (err) { //assertion error is not caught here
console.log(err.stack);
cb(err);
}
I assume the problem is that callbacks that result from async functions like those made in the request module, cannot be trapped by simple error handling.
What is the best way to trap that error?
Should I just flesh out the process.on('uncaughtException') handler? Or is there a better way?
The best way to handle this appears to be Node.js domains, a core module
https://nodejs.org/api/domain.html
it will likely be deprecated soon, but hopefully there will be a replacement that can have similar functionality, because the domain module is saving my ass right now, as I have no other way to trap errors, because the errors might be generated by my users' code, not my code.
I'm new to Promises in JavaScript, and whilst it seems to be working for me to an extent, I'm unable to test the 'reject' value.
I'm passing through an Error, and want to ensure that it is an error and more importantly, that the error code matches what I'm expecting.
return new Promise(function(resolve, reject){
tableService.deleteEntity(config.azureTable.tableName,
visitor.azureEntity(), function (error, response) {
// If successful, go on.
if (!error) {
resolve(response);
}
// If unsuccessful, log error.
else {
/* If we know it's a resourceNotFound
that's causing the error, return that. */
if (error.code === 'ResourceNotFound') {
reject(new Error('Record not found'));
}
// For unexpected errros.
else {
reject(new Error('Table service error (delete): ' + error));
}
}
});
});
The test, in Mocha - using chai and chai-as-promised. Everything else is working (I have 24 passing tests) - but this one has me stuck!
it('return an error when the lookup fails', function (done) {
storage.delete(globalUUID).then(function(sucess) {
done(sucess);
}, function(error) {
expect(error).to.be.an(Error);
done();
});
});
Any help would be greatly appreciated.
You are not using chai-as-promised anywhere. If your first code example is the body of the storage.delete method, then your test should look like:
it('return an error when the lookup fails', function() {
expect(storage.delete(globalUUID)).to.be.rejectedWith(Error);
});