async await fetch catch error in javascript

To await a fetch call and handle any errors that may occur, we can use a try-catch block as shown below:

index.tsx
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();
341 chars
15 lines

Here, we first await the fetch call to get the response from the server. We then check if the response is not ok (i.e., with a status code outside the range 200-299), and then throw an error with a custom message.

Next, we parse the response data by calling await response.json(). If there are no errors in the previous steps, we log the parsed data to the console.

Finally, we wrap the entire operation inside a try-catch block so that any errors that occur in the fetch or the json call can be caught and properly handled by the catch block.

gistlibby LogSnag