How can I stop a thrown error from propagating all the way down the chain? It shows in my catch()
block but it doesn't stop and crashes the server with an uncaught exception.
I am running this as part of a node cron job (node-cron) as:
var cronJob = require('cron').CronJob;
var cron = require('../lib/cron')
var c = new cronJob('* * * * * *', function() {
console.log('Cron starting');
mycode.run();
}, function() {
console.log('Cron executed');
}, true);
c.start();
In my cron.js
module.exports = {
run: function() {
return job.getAndStore().catch(function(e) {
// This prints but it keeps on going so to speak - it doesn't 'catch', just notifies me
console.log('ERROR', e);
});
}
};
Console dump:
Cron starting
ERROR [TypeError: undefined is not a function]
Cron starting
Uncaught Exception
[TypeError: undefined is not a function]
TypeError: undefined is not a function
I have to do this which I know not quite right:
try {
run();
} catch(e) {
console.log('Now it stops')
}
The run()
is part of some cron library that doesn't have any promise support so I am wrapping it in the function to call it.
Edit As I think my issue is related to subsequent calls I believe it has to do with how I handle the Mongo connection on 2+ calls:
// Create a Mongo connection
Job.prototype.getDb = function(id) {
var self = this;
return new P(function(resolve, reject) {
if (!self.db) {
return Mongo.connectAsync(self.options.connection)
.then(function(c) {
self.db = c;
debug('Got new connection');
resolve(c);
});
}
debug('Got existing connection');
resolve(self.db);
});
};
// Fetch stuff
Job.prototype.getAndStore = function(c) {
return this.getDb().then(function() {
throw new Error('Boom');
});
};