improve error when error response is not JSON

This commit is contained in:
Leo Horie 2014-06-04 08:30:12 -04:00
parent 161fbec443
commit 0f4f263441
2 changed files with 19 additions and 1 deletions

View file

@ -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.

View file

@ -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()