JavaScript-də AJAX xətalarının tam əhatəsi

fetch tərəfindən qaytarılan Promise, yalnız şəbəkə xətası baş verdikdə xəta ilə bitir. Əgər server 404 və ya 500 statusu ilə cavab qaytarırsa, Promise uğurla bitəcək, lakin ok statusu false olaraq təyin olunacaq.

Gəlin hər iki növ xətanı əhatə edək:

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

HTTP cavabının pis statusu ilə əlaqəli xətanın da catch bloku tərəfindən tutulması üçün onu throw vasitəsilə irəli ataq:

javascriptbutton.addEventListener('click', function() {
  let promise = fetch('/ajax.html')
  .then(
    response => {
      if (response.ok) {
        return response.text();
      } else {
        throw new Error('pis cavab statusu');
      }
    },
  ).then(
    text => {
      console.log(text);
    }
  ).catch(
    error => {
      console.log(error);
    }
  );
});
Задание 1

Əgər sorğu uğurlu oldusa, səhifənin mətnini çap edin, əks halda nəsə səhv getdisə, xətanı çap edin.