JavaScript-dä AJAX ýalňyşlaryny doly tutmak
fetch tarapyndan yzyna gaýtarylýan wada,
diňe tor ýalňyşy ýüze çykan wagty ýalňyş bilen gutarýar.
Eger serwer 404 ýa-da 500 statusy bilen jogap gaýtarsa,
wada üstünlikli gutarar, ýöne ok statusy
false bolup biler.
Geliň, iki görnüşli ýalňyşlary hem tutalyň:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
console.log('jogabyň ýaman statusy');
return '';
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
HTTP jogabyň ýaman statusy bilen baglanyşykly ýalňyşyň hem
catch blogy tarapyndan tutulmagyny üpjün edeliň.
Bun üçin ony throw arkaly daşary süzeliň:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('jogabyň ýaman statusy');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Eger haýyş üstünlikli bolsa, sahypanyň tekstini çap ediň, we eger bir zat nädogry gidense, ýalňyşy çap ediň.