Úplné zachytenie AJAX chýb v JavaScripte
Promise, ktorý vráti fetch,
sa dokončí s chybou len vtedy, ak nastala
chyba siete. Ak server vrátil odpoveď
so statusom 404 alebo 500,
tak promise bude úspešne dokončený,
ale status ok bude
nastavený na false.
Zachytíme oba typy chýb:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
console.log('zlý status odpovede');
return '';
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Urobíme to tak, aby chyba, spojená
s zlým statusom HTTP odpovede, sa tiež
zachytila blokom catch.
Preto ju pošleme ďalej
cez throw:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('zlý status odpovede');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Vypíšte text stránky, ak požiadavka bola úspešná, a chybu, ak niečo išlo zle.