I'd suggest a wrapper that checks response.ok
which will be true if the response code is 2xx.
Note this statement from the MDN page on fetch()
:
An accurate check for a successful fetch() would include checking that
the promise resolved, then checking that the Response.ok property has
a value of true. An HTTP status of 404 does not constitute a network
error.
Here is a wrapper like this:
function fetchData() {
return fetch.apply(null, arguments).then(response => {
if (!response.ok) {
// create error object and reject if not a 2xx response code
let err = new Error("HTTP status code: " + response.status)
err.response = response
err.status = response.status
throw err
}
return response
})
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…