当我试图将太大的数据插入mongoDb时,我得到了以下错误:MongoError: document is larger than the maximum size 16777216
我知道,这是正常的,但是我无法捕捉到这个错误,并且我的node.js进程退出了。
你能告诉我,如何捕捉这个错误吗?
node example.js:无法捕获错误, example.js进程退出
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
mongoose.connection.on('error', function (err) {
console.log(err);
});
var Cat = mongoose.model('Cat', {name: Object});
setTimeout(function () {
var kitty = new Cat({
name: {
value: 'Zildjian',
data: (new Array(16 * 1024 * 1024)).join("x")
}
});
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
}, 1000);我试图将我的代码打包到一个try...catch中,但这也没有捕捉到错误。
发布于 2016-02-23 15:14:20
因为setTimeout是异步的,并且将回调放在外部,所以调用堆栈提供了错误,因此上升到堆栈的顶部。所以不要使用setTimeout,否则可以添加一个额外的错误处理程序:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
mongoose.connection.on('error', function (err) {
console.log(err);
});
process.on('uncaughtException', function (err) {
if (err.name==='MongoError') {
mongoose.connection.emit('error', err);
} else {
console.log(err);
process.exit(0);
}
});
var Cat = mongoose.model('Cat', {name: Object});
setTimeout(function () {
var kitty = new Cat({
name: {
value: 'Zildjian',
data: (new Array(16 * 1024 * 1024)).join("x")
}
});
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
}, 1000);发布于 2016-02-23 12:15:15
你需要等待连接的启动。等待“打开”事件:
mongoose.connection.once('open', function() {
// Your code goes here
});https://stackoverflow.com/questions/35577212
复制相似问题