From MDN:
A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example.
And:
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
As Garry said in his answer, I suggest creating a middleware to handle the non-successful responses, or just throw exceptions if the status is not 200, or the response.ok is false.
Example (using https://httpstat.us/):
async function getData() {
try {
let response = await fetch('https://httpstat.us/401', {
method: 'GET',
mode: 'cors'
});
if (!response.ok) throw new Error(response.statusText;statusText);
console.log('Dataaa');
return response
} catch (e) {
console.error(e);
return null
}
}
getData()