From 0f4f26344121b94eb7492888f45c107df565ac7e Mon Sep 17 00:00:00 2001 From: Leo Horie Date: Wed, 4 Jun 2014 08:30:12 -0400 Subject: [PATCH] improve error when error response is not JSON --- docs/mithril.request.md | 17 +++++++++++++++++ mithril.js | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/mithril.request.md b/docs/mithril.request.md index 603e6bc8..0b75068c 100644 --- a/docs/mithril.request.md +++ b/docs/mithril.request.md @@ -228,6 +228,23 @@ var file = m.request({ --- +### Using variable data formats + +By default, Mithril assumes both success and error responses are in JSON format, but some servers may not return JSON responses when returning HTTP error codes (e.g. 404) + +You can get around this issue by using `extract` + +```javascript +var nonJsonErrors = function(xhr) { + return xhr.status > 200 ? JSON.stringify(xhr.responseText) : xhr.responseText +} + +m.request({method: "GET", url: "/foo/bar.x", extract: nonJsonErrors}) + .then(function(data) {}, function(error) {console.log(error)}) +``` + +--- + ### Extracting Metadata from the Response The `extract` method can be used to read metadata from HTTP response headers or the status field of an XMLHttpRequest. diff --git a/mithril.js b/mithril.js index b5bc54c5..5311a10e 100644 --- a/mithril.js +++ b/mithril.js @@ -521,7 +521,8 @@ Mithril = m = new function app(window) { deferred[e.type == "load" ? "resolve" : "reject"](response) } catch (e) { - if (e instanceof Error && e.constructor !== Error) throw e + if (e instanceof SyntaxError) throw new SyntaxError("Could not parse HTTP response. See http://lhorie.github.io/mithril/mithril.request.html#using-variable-data-formats") + else if (e instanceof Error && e.constructor !== Error) throw e else deferred.reject(e) } if (xhrOptions.background !== true) m.endComputation()