Handle connection errors

This commit is contained in:
Raymond Feng 2013-10-10 22:47:26 -07:00
parent 4568797aec
commit 64f57a2297
1 changed files with 29 additions and 3 deletions

View File

@ -228,10 +228,13 @@ DataSource.prototype.setup = function(name, settings) {
if (!this.connector) {
throw new Error('Connector is not defined correctly: it should create `connector` member of dataSource');
}
this.connected = !err; // Connected now
if(this.connected) {
this.emit('connected');
} else {
// The connection fails, let's report it and hope it will be recovered in the next call
console.error(err);
this.connecting = false;
}
}.bind(this);
@ -261,11 +264,18 @@ DataSource.prototype.setup = function(name, settings) {
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
} else {
dataSource.connected = false;
dataSource.connecting = false;
dataSource.emit('error', err);
}
cb && cb(err, result);
});
} else {
process.nextTick(function() {
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
cb && cb();
});
}
@ -1453,6 +1463,7 @@ DataSource.prototype.isRelational = function() {
* @returns {boolean}
*/
DataSource.prototype.ready = function(obj, args) {
var self = this;
if (this.connected) {
// Connected
return false;
@ -1460,9 +1471,24 @@ DataSource.prototype.ready = function(obj, args) {
var method = args.callee;
// Set up a callback after the connection is established to continue the method call
this.once('connected', function () {
var onConnected = null, onError = null;
onConnected = function () {
// Remove the error handler
self.removeListener('error', onError);
method.apply(obj, [].slice.call(args));
});
};
onError = function (err) {
// Remove the connected listener
self.removeListener('connected', onConnected);
var params = [].slice.call(args);
var cb = params.pop();
if(typeof cb === 'function') {
cb(err);
}
};
this.once('connected', onConnected);
this.once('error', onError);
if (!this.connecting) {
this.connect();
}