Mongoose.js在保存回调中吞下错误?

时间:2011-10-18 01:55:42

标签: node.js mongoose

这是一个孤立的问题示例:

var assert = require('assert')
var mongoose = require('mongoose')
var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

mongoose.connect("mongodb://localhost/some_db");

var BlogPostSchema = new Schema({
    title     : String
  , body      : String
  , date      : Date
});

var BlogPost = mongoose.model('BlogPost', BlogPostSchema);

var bp = new BlogPost({title: 'blogpost 0'})
bp.save(function(err) {
  console.log("this will print 0")
  assert.equal(1, 1)
  console.log("0 ... no problem")
})

var bp1 = new BlogPost({title: 'blogpost 1'})
bp1.save(function(err) {
  console.log("this will print 1")
  assert.equal(1, 2)
  console.log("this will NOT print")
})

var bp2 = new BlogPost({title: 'blogpost 2'})
bp2.save(function(err) {
  console.log("this will print 2")
  throw "this error is swallowed"
  console.log("this will NOT print")
})

保存回调中抛出的任何错误都不会在控制台中产生输出。执行似乎暂停在该行。

为什么会这样?

是否有更好的方法来编写回调,可能使用Promise?

1 个答案:

答案 0 :(得分:5)

您可以使用连接对象错误事件:

var connection = mongoose.createConnection('mongodb://127.0.0.1/test'),
    BlogPost = connection.model('BlogPost', BlogPostSchema);

connection.on("error", function(errorObject){
  console.log(errorObject);
  ...
});