Sobes.tech
Junior — Middle

Reddedilmiş durumda bir promise kullanırken oluşan hatayı nasıl izleyip işleyebilirsiniz?

sobes.tech yapay zeka

AI'dan gelen yanıt

Reddi ve reddedilmiş durumda bir vaadi kullanırken hatayı izlemek ve yönetmek için .catch() yöntemi veya .then() yönteminin ikinci argümanı kullanılabilir.

.catch() kullanımı örneği:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      return Promise.reject('Ağ hatası');
    }
    return response.json();
  })
  .then(data => {
    console.log('Veriler:', data);
  })
  .catch(error => {
    console.error('Bir hata oluştu:', error);
  });

Ayrıca, try...catch ifadesi ile await kullanılarak asenkron fonksiyon içinde hata yönetimi yapılabilir:

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Ağ hatası');
    }
    const data = await response.json();
    console.log('Veriler:', data);
  } catch (error) {
    console.error('Bir hata oluştu:', error);
  }
}
getData();

Bu yöntemler, reddedilmiş durumda olan hataları düzgün şekilde yakalamayı ve uygulamanın çökmesini önlemeyi sağlar.