From 583418366f38b690cb5be52e137443ec26c789b9 Mon Sep 17 00:00:00 2001
From: alexander-daniel <alex.vados@gmail.com>
Date: Wed, 30 Dec 2015 12:57:54 -0500
Subject: [PATCH] wrap JSON.parse calls in try-catch blocks

---
 index.js | 28 ++++++++++++++++++++++------
 1 file changed, 22 insertions(+), 6 deletions(-)

diff --git a/index.js b/index.js
index fb7186a..01371e9 100644
--- a/index.js
+++ b/index.js
@@ -69,7 +69,13 @@ Plotly.prototype.plot = function(data, graphOptions, callback) {
 
     var req = https.request(options, function (res) {
         parseRes(res, function (err, body) {
-            body = JSON.parse(body);
+
+            /* Try to parse the response */
+            try {
+                body = JSON.parse(body);
+            } catch (e) {
+                callback(e);
+            }
 
             if ( body['stream-status'] != undefined) {
                 self.streamHost = url.parse(body['stream-host']).hostname;
@@ -169,13 +175,23 @@ Plotly.prototype.getFigure = function (fileOwner, fileId, callback) {
 
     var req = https.get(options, function (res) {
         parseRes(res, function (err, body) {
-            if (JSON.parse(body).error) {
-                err = JSON.parse(body).error;
-                callback(err);
-            } else {
-                var figure = JSON.parse(body).payload.figure;
+
+            /* Try to parse the response */
+            try {
+                body = JSON.parse(body);
+            } catch (e) {
+                callback(e);
+            }
+            
+            if (body.error) {
+                callback(body.error);
+            }
+
+            else {
+                var figure = body.payload.figure;
                 callback(null, figure);
             }
+
         });
     });