如何检查 unwrapError

How to check unwrapError

var users = m.request({
  method: "GET",
  url: "hoge.json",
  unwrapSuccess: function(response) {

    return response;
  },
  unwrapError: function(response) {
    //return response.error;
    return "404 error";
  }
});

users.then(function(result) {
  console.log(result); 
});

删除后"hoge.json".

我想捕获“404 错误”,但是

uncaught SyntaxError: Unexpected token <


2016/2/18 添加

我想测试警报 ("unwrapError");

下面的代码总是提醒 ("unwrapSuccess");

如何更改以下代码?

什么是解包错误?

▼js

var users = m.request({
    method: "GET",
    url: "hoge.json",
    unwrapSuccess: function(response) {
          alert ("unwrapSuccess");
          return response;
    },
    unwrapError: function(response) {
          alert ("unwrapError");
          return "error";
    }
});


users.then(function(result) {
  console.log(result); 
});

▼hoge.json

[{"name": "John"}, {"name": "Mary"}]

如果您看一下 mithril's source code,您会发现 m.request 只是 XMLHttpRequest API 的包装。这就是请求的 readyState 属性更改时发生的情况:

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
            options.onload({type: "load", target: xhr})
        } else {
            options.onerror({type: "error", target: xhr})
        }
    }
}

因此只要响应状态不是 2xx,就会调用 mithril 的 unwrapError 回调。

updated the fiddle calling a URL that returns a 500 response 现在调用 unwrapError