In the following code I'm able to catch the exception and print it but for some reason my program breaks there and it makes me to restart the application. Can't I handle it gracefully with out restarting it?
var checkRecordId = function (recordId)
{
if (recordId < 0)
throw new Error ("Record Id can not be 0 or less");
}
var getReport = function (dateRange , recordId)
{
try
{
checkRecordId (recordId);
}
catch (err)
{
console.log (err);
}
}
Related
I'm new to Node.js, Javascript and callbacks. I have a pretty simple program I'm trying to write and I can't get the callbacks to work.
Here's the relevant code:
var keysfetched = false;
var urlsfetched = false;
function setKeysfetched(){
keysfetched = true;
}
function setUrlsfetched(){
urlsfetched = true;
}
//get list of all media in bucket
getKeys(setKeysfetched);
//get a list of all media urls in DB
getUrls(setUrlsfetched);
//check for media in the bucket which is not used
checkKeys();
function getKeys(callback) {
S3.listObjectsV2(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
var contents = data.Contents;
contents.forEach(function (content) {
allKeys.push(content.Key);
});
if (data.IsTruncated) {
params.ContinuationToken = data.NextContinuationToken;
//console.log("get further list...");
getKeys();
}
else{
console.log("end of loop...");
}
}
});
callback()
}
When I run this I get an error : Error [TypeError]: callback is not a function
If I comment out all of the code inside getKeys(), I don't get the error.
This runs just fine:
function getKeys(callback) {
//Hard work here
callback()
}
What am I doing wrong?
You are passing callback and calling it at the bottom of getKeys but inside you are not passing any callback
if (data.IsTruncated) {
params.ContinuationToken = data.NextContinuationToken;
//console.log("get further list...");
getKeys();
}
So it's trying to call undefined which is not a function.
I'm trying to prevent the user to save a piece if it doesn't achieve some requirements.
Currently I'm doing it like this:
self.beforeSave = function(req, piece, options, callback) {
let success = true;
let error = "";
if (Array.isArray(piece._subevents) && piece._subevents.length) {
success = self.checkDateAndTimeCompabilitiyWithChildren(piece);
}
if (!success) {
self.apos.notify(req, "Check the compatibility between parent event and subevents", { type: "error" });
error = "Subevents are not compatible with parent event";
}
callback(error);
};
This works but the problem is it shows 2 errors notifications (the default and my custom), 1 because of callback(error) and 1 because of apos.notify.
Any idea how to stop the item of being saved and only show my notification?
Thanks in advance.
UPDATE 1:
As Tom pointed out, my code looks like this now:
// lib/modules/events/public/js/editor-modal.js
apos.define('events-editor-modal', {
extend: 'apostrophe-pieces-editor-modal',
construct: function(self, options) {
self.getErrorMessage = function(err) {
if (err === 'incompatible') {
apos.notify('A message suitable for this case.', { type: 'error' });
} else {
apos.notify('A generic error message.', { type: 'error' });
}
};
}
});
// lib/modules/events/index.js
var superPushAssets = self.pushAssets;
self.pushAssets = function() {
superPushAssets();
self.pushAsset("script", "editor-modal", { when: "user" });
};
self.beforeSave = async function(req, piece, options, callback) {
return callback("incompatible")
};
For testing purposes I'm just returning the error in beforeSave. The problem is that an exception is being thrown in the browser console and the modal is not properly rendered again. Here's a screenshot about what I'm talking:
I'm trying to debug it and understand what's happening but no clue yet.
In your server-side code:
self.beforeSave = function(req, piece, options, callback) {
let success = true;
if (Array.isArray(piece._subevents) && piece._subevents.length) {
success = self.checkDateAndTimeCompabilitiyWithChildren(piece);
}
if (!success) {
return callback('incompatible');
}
return callback(null);
};
And on the browser side:
// in lib/modules/my-pieces-module/public/js/editor-modal.js
apos.define('my-pieces-module-editor-modal', {
extend: 'apostrophe-pieces-editor-modal',
construct: function(self, options) {
self.getErrorMessage = function(err) {
if (err === 'incompatible') {
return 'A message suitable for this case.';
} else {
return 'A generic error message.';
}
};
}
});
If the error reported by the callback is a string, it is passed to the browser. The browser can then recognize that case and handle it specially. 'my-pieces-module-editor-modal' should be substituted with the name of your pieces module followed by -editor-modal.
I'm new to NodeJs and code I'm working with is using Q framework for promises.
And it seems that I don't understand the 'Q' framework too well, I'm running into a case when promises are returning too early.
Here is my code:
BridgeInfo.getBridgeInfo(exten)
.then(function processBridgeInfo(bridge_info) {
console.log("Nitesh -- bridge info is back, yay");
if (bridge_info !== undefined) {
conf_bridge = new VoxConfBridge(ari);
conf_bridge.init(bridge_info);
/**Add the bridge to the bridgeList**/
bridgeList[conf_bridge.bridge.id] = conf_bridge;
console.log("Bridge ID to register is "+ conf_bridge.bridge.id);
self.registerEvents(conf_bridge.bridge);
conf_bridge.registerUser(event, false, channel);
} else {
console.log("Unknown extension [" + exten + "] blocking it");
ChannelDriver.blockChannel(ari, channel.id);
}
})
.catch(function handleError(err) {
console.error("Nitesh -- [voxbridgemanager] error occured "+err);
});
The above code calls a function getBridgeInfo, this function is supposed to do some DB queries and return the result.
Here is the code in getBridgeInfo
BridgeInfo.getBridgeInfo = Q.async(function(bridge_identifier) {
console.log("Nitesh -- Getting the bridge info for ["+ bridge_identifier + "]");
if (bridge_identifier !== undefined) {
db.getConfBridgeProfile(bridge_identifier)
.then(function processBridgeProfile(result) {
if (result !== undefined) {
console.log("Nitesh -- Bridge Info is "+ JSON.stringify(result));
var bridge_info = new BridgeInfo();
bridge_info.init(result)
.then (function bridgeInfoInitDone() {
return bridge_info;
})
.catch( function handleError(err) {
console.error("Nitesh ---[bridgeInfoInit] Error is "+ err);
});
}
else {
console.log("Can't find any bridge profile for this identifier ["+ bridge_identifier + "]");
}
}, function handleError(err) {
console.error("Failed to retrieve bridgeInfo");
});
} else {
console.error("Received an invalid identifier");
}
});
**When I run this code, I see that in my main code,which calls getBrigeInfo, it hits its catch error handler even before getBRidgeInfo has executed completely, getBridgeInfo's SQL query results appear afterwards.
I think the way I'm using promises isn't being done correctly, any explanations please
Your missing the key part of what promises can do.
You should not need to do any catch statements in your getBridgeInfo. You should return the whole promise that gets the SQL data... and handle it in your first block of code BridgeInfo.getBridgeInfo(exten)
Assuming that db.getConfBridgeProfile(bridge_identifier); returns a promise
Example:
BridgeInfo.getBridgeInfo = function(bridge_identifier) {
console.log("Nitesh -- Getting the bridge info for ["+ bridge_identifier + "]");
if (bridge_identifier !== undefined) {
return Q.fcall(function () {
throw new Error("Received an invalid identifier");
});
}
return db.getConfBridgeProfile(bridge_identifier);
}
I've also seperated out your process query... keep things simple.
BridgeInfo.processBridgeProfile = function(result) {
if (result !== undefined) {
console.log("Nitesh -- Bridge Info is "+ JSON.stringify(result));
var bridge_info = new BridgeInfo();
return bridge_info.init(result);
}else{
return Q.fcall(function () {
throw new Error("Can't find any bridge profile for this identifier ["+ bridge_identifier + "]");
});
}
Return promises and handle the catch in the main function. Your getting stuck in handling a catch, the SQL results are not getting returned like they should.
Call:
BridgeInfo.getBridgeInfo(bridge_identifier).then(function(result){
return BridgeInfo.processBridgeProfile(result)
}).then(function(){
//Do the rest here
}).catch(function(){
//One catch to rule them all :)
});
I am using the sftps NPM to connect to a SFTP server using username/password authentication and upload a file. This works beautifully when successful; however, if provided invalid authentication information, after several minutes it emits an ECONNRESET error which crashes my entire application.
Looking at the source of the sftps module, it appears to use child_process.spawn to run the shell commands, and looks like it should be capturing any errors gracefully:
var sftp = spawn(shellCmd, shellOpts);
var data = "";
var error = "";
sftp.stdout.on('data', function (res) {
data += res;
});
sftp.stderr.on('data', function (res) {
error += res;
});
function finished(err) {
error = error.split('\n').filter(function(line) {
if (/^Connected to /.test(line)) return false;
return true;
}).join('\n');
data = data.split('\n').filter(function(line) {
if (/^sftp> /.test(line)) return false;
return true;
}).join('\n');
if (callback) {
if (err) {
callback(err, { error: error || null, data: data });
} else if (error) {
callback(null, { error: error, data: data });
} else {
callback(null, { error: null, data: data });
}
callback = null;
}
}
sftp.on('error', finished);
sftp.on('exit', function (code) {
if (code === 0) {
finished();
} else {
finished('Nonzero exit code: ' + code);
}
});
sftp.stdin.write(cmdString, 'utf8');
It looks like it has hooked into the stderr stream as well as capturing the error and exit events on the sub-process.
What else can I do to capture this ECONNRESET error and log it without killing the application?
Don't know if you're having the same problem that I was having, but I eventually solved it by attaching an event to stdin.on("error"). You could try this to see if that's the problem:
sftp.stdin.on("error", function (e)
{
console.log("STDIN ON ERROR");
console.log(e);
});
I have this simple js script:
var cb = require('couchbase');
var bucket;
var connectionSettings = {
'user':'test-bucket',
'password':'test',
'hosts':['localhost:8091'],
'bucket':'test-bucket'
};
cb.connect(connectionSettings, function(e, bucket) {
if (e) {
errorHandler('connect', e);
} else {
console.log('Connection established!');
bucket.get('testObject', function(e, doc) {
if(e) {
errorHandler('get', e);
} else {
console.log(doc);
}
});
}
});
function errorHandler(from, e) {
console.log('Function: ' + from);
console.log(e.message);
console.log(e.stack);
}
After executing it a connection is being established, but when I try to get the document with id 'a' in this test case I get the following error:
syd#HP-Notebook:~/Desktop$ node test.js
Connection established!
Function: get
Network error
Error: Network error
at makeError (/home/syd/node_modules/couchbase/lib/bucket.js:578:18)
at getParsedHandler (/home/syd/node_modules/couchbase/lib/bucket.js:625:17)
node: ../src/ioplugin.cc:496: virtual int Couchnode::IoOps::updateEvent(lcb_socket_t, void*, short int, void*, void (*)(lcb_socket_t, short int, void*)): Assertion `socket != __null' failed.
Aborted (core dumped)
Furthermore here are the code snippets where these errors occur in bucket.js.
578:
function makeError(conn, errorCode) {
// Early-out for success
if (errorCode == 0) {
return null;
}
// Build a standard NodeJS Error object with the passed errorCode
var errObj = new Error(conn.strError(errorCode)); // <- 578 error here
errObj.code = errorCode;
return errObj;
}
625:
function getParsedHandler(data, errorCode, key, cas, flags, value) {
// if it looks like it might be JSON, try to parse it
if (/[\{\[]/.test(value)) {
try {
value = JSON.parse(value);
} catch (e) {
// console.log("JSON.parse error", e, value)
}
}
var error = makeError(data[1], errorCode); // <- 625 error here
data[0](error, value, {
id : key,
cas: cas,
flags : flags
});
}
Any ideas why this is happening ?
P.S. I have no issues mining data from PHP.
It fails for the same reason as in this question. Downgrading libcouchbase to 2.0.7 should solve issue.
UPD: "Fixed" in new couchbase nodejs library release 1.0.0-beta.