fetch should throw an error when it receives a 404
tobireif opened this issue · comments
When there's eg a 404, fetch should throw an error, so that I can .catch() and handle it. (The error related code in the readme should be in fetch by default.)
You would think so, but that's not per spec. The spec only rejects the promise if there was an error making or receiving the response. A HTTP 404 should be treated as a "successful" response and is up to the user to decide what to do with such response.
If you want to reject non-20x responses, you can make your own wrapper:
function myFetch(url, options) {
if (options == null) options = {}
if (options.credentials == null) options.credentials = 'same-origin'
return fetch(url, options).then(function(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
var error = new Error(response.statusText || response.status)
error.response = response
return Promise.reject(error)
}
})
}
This resembles XMLHttpRequest in its handling of same-domain cookies and successful responses.
Actually, in this specific case, I want to accept only status 200, so having my own code "if (response.status === 200) ..." instead of "if (response.status >= 200 && response.status < 300) ..." is handy.
Thanks for the wrapper code, but for my project, the following is sufficient AFAICS:
function fetchStatusHandler(response) {
if (response.status === 200) {
return response;
} else {
throw new Error(response.statusText);
}
}
(Inside a Promise wrapper containing additional stuff:)
fetch(url)
.then(
fetchStatusHandler
).then(function(response) {
return response.blob();
}).then(function(blob) {
resolve(blob.size);
}).catch(function(error) {
reject(error);
});
Also: related: whatwg/fetch#60 .