JavaScript-da AJAX xatolarini to'liq ushlash
fetch tomonidan qaytariladigan promis,
faqat tarmoq xatosi yuz berganda
xato bilan tugaydi. Agar server
404 yoki 500 holati bilan javob qaytarsa,
unda promis muvaffaqiyatli tugaydi,
lekin ok holati
false ga o'rnatiladi.
Keling, ikkala turdagi xatolarni ushlaymiz:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
console.log('yomon holat javobi');
return '';
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
HTTP javobining yomon holati bilan bog'liq xatolik ham
catch bloki tomonidan ushlanishi uchun
uni throw orqali
keyingiga otamiz:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('yomon holat javobi');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});
Agar so'rov muvaffaqiyatli bo'lsa, sahifa matnini chiqaring, va agar nimadir noto'g'ri ketgan bo'lsa, xatoni chiqaring.