Exceptions during AJAX requests in JavaScript
If an exception occurs while executing
an AJAX request (for example, the Internet
is interrupted), then the promise will
end with an error. We can catch this
error in a convenient way, for example,
through catch:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
return response.text();
},
).then(
text => {
console.log(text);
}
).catch(
error => {
alert(error);
}
);
});
Output a text of a page if the request was successful, and an error if there was a network error.