How to handle errors in fetch using javascript?

Member

by daisha , in category: Javascript , 5 months ago

How to handle errors in fetch using javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 5 months ago

@daisha 

To handle errors in fetch using JavaScript, you can use the .catch() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    // Handle successful response
    console.log(data);
  })
  .catch(error => {
    // Handle error
    console.error('Error:', error);
  });


In this example, the .then() method is used to check if the response from the server is not ok. If the response is not ok, it throws an error. The .catch() method is then used to catch any errors that occur in the promise chain. Inside the catch block, you can handle the error accordingly.


You can modify the error handling logic inside the .catch() block according to your application's needs, such as displaying a specific error message or taking alternative actions.