HomeToolsAbout

HTTP Response Codes

Success

response.ok property lets you distinguish good from bad HTTP response statuses

  • property is set to true only if the response has status (200-299)

Errors

Client errors (400499) Server errors (500599)

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

  • Without explicit error handling, the function returns a string instead of an Error which is considered a completed HTTP request

Throwing 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' });
AboutContact