4 ms·
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:/
by marktucker 11y ago
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 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?");
}
});
- Zecc 11y agoFWIW, 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