2

Question

When mithril's m.request fails with a timeout or a network error, the error returned is simply null. This makes it impossible to distinguish between

  1. timeouts
  2. a lack of internet connection
  3. other kinds of errors.

Is there a way to determine this information?

Demo

In the snippet below, the request will timeout every time, since the limit is 1ms. The error returned is null. If you change it to 1000ms, it will work. If you turn your wifi off, and try again, it will return another null error.

const Test = {
  controller: function() {

    var user = m.prop('Waiting...');
    var error = m.prop();

    var args = {
      method: 'GET',
      url: "https://jsonplaceholder.typicode.com/users",
      config: function(xhr) {
        xhr.timeout = 1;
      }
    };

    function refreshUser() {
      m.request(args)
       .then( users => user(users[0].name), error);
    }
    return { user, error, refreshUser};
  },
  view: function(ctrl) {
    return m('div', [
      m('div',  'Fetched User: ' + ctrl.user()),
      m('div', 'Network Error: ' + ctrl.error()),
      m('button', {onclick: ctrl.refreshUser }, 'Refresh User')
    ]); 
  }
}
m.mount(document.body, Test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.5/mithril.min.js"></script>
Community
  • 1
  • 1
Jonah
  • 15,806
  • 22
  • 87
  • 161

1 Answers1

2

There is a parameter you can pass to m.request called extract, which will contain the xhr response. Hopefully you can find what you need there.

Example from the m.request docs:

var extract = function(xhr, xhrOptions) {
    if (xhrOptions.method == "HEAD") return xhr.getResponseHeader("x-item-count")
    else return xhr.responseText
}

m.request({method: "POST", url: "/foo", extract: extract});
ciscoheat
  • 3,719
  • 1
  • 35
  • 52