async await fetch error response.ok in javascript

You can use the fetch() function with error handling in conjunction with async/await. Here's an example:

index.tsx
async function getData() {
  try {
    const response = await fetch('https://example.com/data.json');
    if (!response.ok) {
      throw new Error('Network response not ok.');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

getData();
328 chars
15 lines

In this example, we have a function called getData() that uses async/await to handle the asynchronous fetch() call.

We check if the response.ok property is true. If not, we throw a new error.

If the response.ok property is true, we can then parse the response body using the .json() method.

If there is an error at any point during the execution of getData(), we catch it and log an error message to the console.

gistlibby LogSnag