diff --git a/lib/HttpAction.js b/lib/HttpAction.js index a784985..da58e75 100644 --- a/lib/HttpAction.js +++ b/lib/HttpAction.js @@ -10,10 +10,19 @@ exports.runAction = function( post_options, post_data, https_action, callback){ var abstractResponse = function(res){ res.setEncoding('utf8'); res.on('data', function (String_chunk) { - var JSON_chunk = JSON.parse(String_chunk); + var JSON_chunk; + try { + JSON_chunk = JSON.parse(String_chunk); + } catch (err) { + err.source = String_chunk; + return callback(new Response(null, null, { err: err })); + } var response = new Response(JSON_chunk, String_chunk); callback(response); }); + res.on('error', function (err) { + callback(new Response(null, null, { err: err })); + }); }; if (https_action !== true) { post_options.port = 80; diff --git a/lib/Response/Abstract.js b/lib/Response/Abstract.js index 21ec76e..5016321 100644 --- a/lib/Response/Abstract.js +++ b/lib/Response/Abstract.js @@ -2,7 +2,13 @@ var Success = require('./Success'); var Err = require('./Err'); -function CallbackRes(JSON_chunk, String_chunk){ +function CallbackRes(JSON_chunk, String_chunk, option){ + option = option || {}; + if (option.err) { + var response = Err.buildResponseFromErrorObject(option.err); + JSON_chunk = JSON_chunk || response; + String_chunk = String_chunk || JSON.stringify(response); + } this.JSON_chunk = JSON_chunk; this.String_chunk = String_chunk; } @@ -102,8 +108,11 @@ CallbackRes.prototype = { getErrorDetails: function(){ return Err.getParameter('error',this.JSON_chunk); - } + }, + getErrorObject: function(){ + return Err.getParameter('err',this.JSON_chunk); + } }; module.exports = CallbackRes; \ No newline at end of file diff --git a/lib/Response/Err.js b/lib/Response/Err.js index dc932ac..14e0bea 100644 --- a/lib/Response/Err.js +++ b/lib/Response/Err.js @@ -2,4 +2,22 @@ exports.getParameter = function(parameter, JSON_chunk){ return JSON_chunk[parameter]; -}; \ No newline at end of file +}; + +exports.buildResponseFromErrorObject = function(err){ + if (typeof err.toJSON === 'undefined') { + err.toJSON = function(){ + return { + message: this.message, + code: this.code, + source: this.source + }; + }; + } + return { + type: 'Error', + code: 'ERROR_OBJECT', + error: err.message, + err: err + }; +}