diff --git a/lib/datasource.js b/lib/datasource.js index bedd4ee8..97ce57c2 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -2066,13 +2066,26 @@ DataSource.prototype.ready = function (obj, args) { // Set up a callback after the connection is established to continue the method call var onConnected = null, onError = null, timeoutHandle = null; - onConnected = function () { + onConnected = function() { // Remove the error handler self.removeListener('error', onError); if (timeoutHandle) { clearTimeout(timeoutHandle); } - method.apply(obj, [].slice.call(args)); + var params = [].slice.call(args); + try { + method.apply(obj, params); + } catch (err) { + // Catch the exception and report it via callback + var cb = params.pop(); + if (typeof cb === 'function') { + process.nextTick(function() { + cb(err); + }); + } else { + throw err; + } + } }; onError = function (err) { // Remove the connected listener @@ -2083,7 +2096,9 @@ DataSource.prototype.ready = function (obj, args) { var params = [].slice.call(args); var cb = params.pop(); if (typeof cb === 'function') { - cb(err); + process.nextTick(function() { + cb(err); + }); } }; this.once('connected', onConnected);