Complete AJAX error catching in JavaScript

A promise that returns fetch only fails if a network error occurs. If a server returned a response with the status 404 or 500, then the promise will be completed successfully, but the ok status will be set to false.

Let's catch both types of errors:

button.addEventListener('click', function() { let promise = fetch('/ajax.html') .then( response => { if (response.ok) { return response.text(); } else { console.log('bad response status'); return ''; } }, ).then( text => { console.log(text); } ).catch( error => { console.log(error); } ); });

Let's make it so that an error associated with the bad status of the HTTP response is also caught by a catch-block. To do this, let's throw it further using throw:

button.addEventListener('click', function() { let promise = fetch('/ajax.html') .then( response => { if (response.ok) { return response.text(); } else { throw new Error('bad response status'); } }, ).then( text => { console.log(text); } ).catch( error => { console.log(error); } ); });

Output a text of a page if the request was successful, and an error if something went wrong.

enru