From 3e9bd13bffccfe9206bde2fc8965c60cb4f5632d Mon Sep 17 00:00:00 2001 From: Lalit Kapoor Date: Sun, 31 Jul 2011 18:41:13 -0500 Subject: [PATCH] updated to support parsing errors --- lib/restler.js | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/lib/restler.js b/lib/restler.js index da68f6b..ca29645 100644 --- a/lib/restler.js +++ b/lib/restler.js @@ -110,30 +110,29 @@ mixin(Request.prototype, { response.on('end', function() { if (self.options.parser) { - self.options.parser.call(response, body, function(parsedData) { - - self._fireEvents(parsedData, response); - }); + self.options.parser.call(response, body, function(error, parsedData) { + self._fireEvents(error, parsedData, response); + }); } else { - self._fireEvents(body, response); + self._fireEvents(null, body, response); } }); } }, - _respond: function(type, data, response) { + _respond: function(type, error, data, response) { if (this.options.originalRequest) { this.options.originalRequest.emit(type, data, response); } else { - this.emit(type, data, response); + this.emit(type, error, data, response); } }, - _fireEvents: function(body, response) { - if (parseInt(response.statusCode) >= 400) this._respond('error', body, response); - else this._respond('success', body, response); + _fireEvents: function(error, body, response) { + if (parseInt(response.statusCode) >= 400) this._respond('error', error, body, response); + else this._respond('success', error, body, response); - this._respond(response.statusCode.toString().replace(/\d{2}$/, 'XX'), body, response); - this._respond(response.statusCode.toString(), body, response); - this._respond('complete', body, response); + this._respond(response.statusCode.toString().replace(/\d{2}$/, 'XX'), error, body, response); + this._respond(response.statusCode.toString(), error, body, response); + this._respond('complete', error, body, response); }, _makeRequest: function() { var self = this; @@ -205,7 +204,11 @@ var parsers = { callback(data); }, json: function(data, callback) { - callback(data && JSON.parse(data)); + try { + return callback(null, data && JSON.parse(data)); + } catch(error){ + callback(error, data); + } } }