response.ok
property lets you distinguish good from bad HTTP response statuses
true
only if the response has status (200
-299
)Client errors (400
–499
)
Server errors (500
–599
)
Errors must be explicitly handled when making a fetch request
async function fetchResultsIn404() { const response = await fetch('/error'); response.ok; // => false response.status; // => 404 const text = await response.text(); return text; // 'Page not found' }
When above code is executed, the resource request results in an error
async function fetchBadStatus() { const response = await fetch('/oops'); if (!response.ok) { const message = `An error has occured: ${response.status}`; throw new Error(message); } const movies = await response.json(); return movies; } fetchBadStatus().catch(error => { error.message; // 'An error has occurred: 404' });