Skip to content

Error handling when fetch failed #74513

Answered by Dobefu
Michahide asked this question in Help
Discussion options

You must be logged in to vote

Hiya!

This is because the fetch function throws when it cannot get a response. The response.ok check is correct, but is only used to check if the response has a 2XX HTTP status code.
The following example should work for you:

export default async function Home() {
  let products: Products[];

  try {
    const token = await getAccessToken();
    const response = await fetch('https://localhost:8000/v1/products');

    if (!response.ok) {
      throw new Error(response.statusText);
    }

    const products = response.json();
    products = products.data;
  }
  catch (e) {
    console.error(`Failed to fetch products: ${e}`);
  }

  if (!products.length) {
    // Some error handling here, li…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@icyJoseph
Comment options

@Michahide
Comment options

Answer selected by Michahide
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
3 participants