gett/mongojs — Issue #10: using mongojs with asynchronous trycatch module
Author: jayyy0v
Created: 2011-12-26 16:25:42+00:00
State: open

Hi,

I love using mongojs. Thanks to its clean syntax.

Recently, I had come across an interesting npm package named 'trycatch' ( https://github.com/CrabDude/trycatch ) that implements try..catch for asynchronous code. It catches an exception that is thrown by an async code, as if it had happened in a sync code. While it works with async file readings., etc, I am unable to succeed with mongojs. Out of curiosity, I went ahead to try with mongo-native code and see that it works well. I am able to throw an exception in any of the deep-down async callback and catch it.

Could you guys help me out to figure out a way to use it with mongojs ?

working: async file reading

```javascript
var trycatch = require('trycatch');

trycatch(function init() {
fs.readFile(__filename, function (err, data) {
console.log(''+data);
throw new Error("yahoooo. will be caught");
});
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);
```

not working: mongojs async find()

```javascript
trycatch(function init() {
db.users.find(function (err, doc) {
console.log(doc);
throw new Error("yahoooo. You can't catch me");
});
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);
```

working : mongo-native find()

```javascript
trycatch(function init() {
testmongo();
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);

function testmongo() {
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;

var host = 'localhost';
var port = 27017;

console.log("Connecting to " + host + ":" + port);
var db = new Db('mydb', new Server(host, port, {}));

db.open(function(err, db) {
db.collection('users', function(err, collection) {
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
console.dir(item);
throw new Error("yahoooo. will be caught");
});
});
});
});
}
```