diff --git a/lib/graph.js b/lib/graph.js index d17bee4..518bece 100644 --- a/lib/graph.js +++ b/lib/graph.js @@ -190,12 +190,17 @@ Graph.prototype.get = function () { return; } - body = { ...JSON.parse(body), headers: res.headers }; - if (~res.headers['content-type'].indexOf('image')) { + if (res.headers['content-type'] && ~res.headers['content-type'].indexOf('image')) { body = { - image: true - , headers: res.headers + image: true + , headers: res.headers }; + } else { + try { + body = { ...JSON.parse(body), headers: res.headers }; + } catch (e) { + // parsing failed, pass raw body to end() + } } self.end(body); @@ -233,7 +238,11 @@ Graph.prototype.post = function() { return; } - body = { ...JSON.parse(body), headers: res.headers }; + try { + body = { ...JSON.parse(body), headers: res.headers }; + } catch (e) { + // if parsing fails, we pass the raw body to end() + } self.end(body); }) .on('error', (err) => { diff --git a/tests/graph.test.js b/tests/graph.test.js index c782f52..bbbf079 100644 --- a/tests/graph.test.js +++ b/tests/graph.test.js @@ -2,7 +2,8 @@ var graph = require("../index") , FBConfig = require("./config").facebook , vows = require("vows") , events = require("events") - , assert = require("assert"); + , assert = require("assert") + , request = require("request"); var testUser1 = {} @@ -277,6 +278,31 @@ vows.describe("graph.test").addBatch({ } } } +}).addBatch({ + "Hardening JSON Parsing": { + "When receiving a non-JSON response": { + topic: function () { + var callback = this.callback + , originalGet = request.get; + + request.get = function (options, cb) { + var res = { headers: { 'content-type': 'text/html' } } + , body = '{"foo": bar}'; // Malformed JSON + setImmediate(function () { cb(null, res, body); }); + return { on: function () { return this; } }; + }; + + graph.get('/me', function (err, res) { + request.get = originalGet; + callback(err, res); + }); + }, + "it should return an error instead of crashing": function (err, res) { + assert.isNotNull(err); + assert.equal(err.message, 'Error parsing json'); + } + } + } }).addBatch({ "When tests are over": { topic: function () {