From cd0cc0217d80d3c0a6b0744fcaa145cf7575ef2f Mon Sep 17 00:00:00 2001 From: Hiroyuki Sano Date: Mon, 10 Aug 2015 14:53:06 +0900 Subject: [PATCH] Show an error message when a response does not have a JSON text --- extensions/chrome/js/background.js | 12 +++++++++++- lib/web_console/templates/console.js.erb | 24 ++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/extensions/chrome/js/background.js b/extensions/chrome/js/background.js index f364bfef..96da3c3b 100644 --- a/extensions/chrome/js/background.js +++ b/extensions/chrome/js/background.js @@ -40,11 +40,21 @@ function initPanelMessage() { function initReqRes() { chrome.runtime.onMessage.addListener(handleMessage); + function extractProps(xhr) { + var props = {}; + for (var key in xhr) { + if (typeof xhr[key] === 'string' || typeof xhr[key] === 'number') { + props[key] = xhr[key]; + } + } + return props; + } + function handleMessage(req, sender, sendResponse) { if (req.type === 'request') { var url = tabInfo[req.tabId].remoteHost + '/' + req.url; REPLConsole.request(req.method, url, req.params, function(xhr) { - sendResponse({ status: xhr.status, responseText: xhr.responseText }); + sendResponse(extractProps(xhr)); }); } return true; diff --git a/lib/web_console/templates/console.js.erb b/lib/web_console/templates/console.js.erb index 5a961217..de55f2a7 100644 --- a/lib/web_console/templates/console.js.erb +++ b/lib/web_console/templates/console.js.erb @@ -80,13 +80,33 @@ REPLConsole.prototype.commandHandle = function(line, callback) { return status >= 200 && status < 300 || status === 304; } + function parseJSON(text) { + try { + return JSON.parse(text); + } catch (e) { + return null; + } + } + + function getErrorText(xhr) { + if (!xhr.status) { + return "<%= t 'errors.connection_refused' %>"; + } else { + return xhr.status + ' ' + xhr.statusText; + } + } + putRequest(self.getUrl(), params, function(xhr) { - var response = JSON.parse(xhr.responseText); + var response = parseJSON(xhr.responseText); var result = isSuccess(xhr.status); if (result) { self.writeOutput(response.output); } else { - self.writeError(response.output); + if (response && response.output) { + self.writeError(response.output); + } else { + self.writeError(getErrorText(xhr)); + } } callback(result, response); });