Mark As Completed Discussion

Error Handling

When working with APIs in React, it's important to handle errors that may occur during API requests. Error handling allows us to gracefully handle any issues that arise and provide feedback to the user.

To handle errors in API requests, we can use try...catch blocks. Within the try block, we write the code that makes the API request. If an error occurs, it will be caught by the catch block.

Here's an example of how to handle errors during an API request in React:

JAVASCRIPT
1try {
2  const response = await fetch('https://api.example.com/data');
3
4  if (!response.ok) {
5    throw new Error('Request failed with status: ' + response.status);
6  }
7
8  const data = await response.json();
9
10  // Process the data
11} catch (error) {
12  console.error(error);
13}

In this example, we use the fetch function to make an API request. If the response is not ok, meaning the request was not successful (e.g., a 404 error), we throw an Error with a customized error message.

Inside the catch block, we log the error to the console using console.error. You can also display an error message to the user or perform any necessary error handling tasks.

Remember to replace the API endpoint and customize the error handling logic to suit your specific application's needs.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment