Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js swallows errors in save callback?

Here is an isolated example of the problem:

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")
})

Any error thrown inside the save callback produces no output in the console. The execution seems to pause at that line.

Why does this happen?

Is there a better way to write callbacks, perhaps using a Promise?

like image 250
StereoSteve Avatar asked Oct 18 '11 01:10

StereoSteve


1 Answers

You can use connection object error event:

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

connection.on("error", function(errorObject){
  console.log(errorObject);
  ...
});
like image 143
Erhan Avatar answered Oct 23 '22 05:10

Erhan