How to check unwrapError

253 Views Asked by At
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); 
});

After delete "hoge.json".

I want to catch "404 error",but

uncaught SyntaxError: Unexpected token <


2016/2/18 add

I want to test alert ("unwrapError");

Below code is always alert ("unwrapSuccess");

How to change below code?

What is the unwrapError?

▼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"}]
1

There are 1 best solutions below

1
On BEST ANSWER

If you take a look at mithril's source code you will see that m.request is just a wrapper for the XMLHttpRequest API. And that's what happens when the request's readyState attribute changes:

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})
        }
    }
}

So mithril's unwrapError callback will be called whenever the response status is not a 2xx.

I updated the fiddle calling a URL that returns a 500 response and now the unwrapError is called.