【发布时间】:2015-03-01 18:10:14
【问题描述】:
如何阻止抛出的错误在整个链条中传播?它显示在我的 catch() 块中,但它不会停止并导致服务器崩溃并出现未捕获的异常。
我将其作为节点 cron 作业 (node-cron) 的一部分运行:
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();
在我的 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);
});
}
};
控制台转储:
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
我必须这样做,但我知道这不太对:
try {
run();
} catch(e) {
console.log('Now it stops')
}
run() 是某些不支持任何承诺的 cron 库的一部分,因此我将其包装在函数中以调用它。
编辑我认为我的问题与后续调用有关,我认为这与我在 2 次以上调用中处理 Mongo 连接的方式有关:
// 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');
});
};
【问题讨论】:
-
“它不会停止并导致服务器崩溃”是什么意思?错误究竟是在哪里引发的?如果你的
catch回调被调用,你应该是安全的。 -
您的代码中还有另一个问题 - 向我们展示堆栈跟踪。
-
添加了更多代码 - 它在 promise 的 catch 块中打印出我的错误,然后“继续”,可以这么说,导致整个应用程序崩溃。我不确定我的错误在哪里
标签: javascript promise bluebird