Hacker News new | past | comments | ask | show | jobs | submit login




Fetch is great and there's a tiny polyfill from GitHub to patch IE and Safari https://github.com/github/fetch


I find fetch very painful to use since the promises don't reject on non-2XX! I use axios instead. This is especially so sad when using async/await :( https://github.com/whatwg/fetch/issues/18

  fetch(url)
    .then((res) => {
      if (res.statusCode < 200 || res.statusCode > 299) {
        throw new Error("Why do I have to write this with every request?");
      }
    });


FWIW, the Response object has the `ok` property [1] as a shorcut. It is equivalent to testing whether status is between 200 and 299.

If it's really that important to you, you can always create your own wrapper around fetch

    function fetch2(uri) {
       return fetch(uri).then( (res) => {
         if (res.ok) {
           return Promise.resolve(res);
         } else {
           return Promise.reject("Request failed with status "+res.status+" ("+res.statusText+")");
         }
       } );
    }

    fetch2('some-url')
      .then( (res) => {
       console.log('Success', res.status, res.statusText);
      })
      .catch( (err) => {
       console.log(err);
      });

  [1]: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: