Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to catch errors after fetch in ReactJS

Understanding fetch in ReactJS

To start our exploration on catching errors in ReactJS, let's first understand the fetch function. In the simplest terms, fetch is like a courier service in the world of web development. It's a function that helps us to request information from somewhere else (usually a server) and bring it into our application.

Think of it like this: you (the ReactJS application) are at home, and you need a pizza (the data). So you call up your favorite pizza place (the server), and ask them to deliver a pizza to your house. The fetch function is like the delivery person in this analogy.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

The Importance of Error Handling

Our pizza delivery analogy works great when everything goes smoothly. But what happens when things go wrong? What if the pizza place is closed, or the delivery person gets lost? These are the types of situations where error handling becomes important.

Error handling is like having a plan B for when things go wrong. Instead of your code crashing unexpectedly, you can decide what should happen when an error occurs. This can make your application more robust and user-friendly.

Catching Errors After fetch

Now, let's see how to catch errors after using the fetch function in a ReactJS application.

One might think that if the server is down or the requested data is not available, the fetch function will throw an error. However, this is not the case. The fetch function only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” A valid HTTP response, even a 404 or 500, will result in a resolved promise.

So, if we want to handle these kinds of errors, we need to do it manually. We can do this by checking the 'ok' status of the Response object. If it's not 'ok' (if the HTTP status is not between 200-299), we throw an error.

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log('There has been a problem with your fetch operation: ', error.message));

Going back to our pizza delivery analogy, this is like checking whether the pizza has arrived in good condition before accepting the delivery. If the pizza is not okay (maybe it's the wrong order, or it's not cooked properly), we complain to the pizza place.

Using Async/Await

Alternatively, we can use the modern async/await syntax to handle errors in fetch. The async/await syntax allows us to write asynchronous code in a more synchronous manner, which can make it easier to read and understand.

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch(error) {
    console.log('There has been a problem with your fetch operation: ', error.message);
  }
}

fetchData();

In this code, we create an async function called fetchData. Inside this function, we use the try/catch block to handle errors. First, we try to fetch the data and process the response. If anything goes wrong during this process, we catch the error and handle it accordingly.

Conclusion

In the bustling city of web development, fetch plays the crucial role of a delivery person, bringing data from the server to our React application. However, just like in real life, not every delivery goes as planned. It's important to prepare for these unexpected situations by implementing error handling in our code.

Remember, error handling in web development is not just about preventing crashes — it's also about providing a seamless and friendly user experience. When done right, error handling can transform potential mishaps into opportunities for user engagement. So, next time you're coding, don't just focus on the happy path. Spare a thought for what could go wrong, and arm your code with the safety net of error handling. Happy coding!