0

I have multiple API calls in the getStaticProps. I want handle errors for each API call individually. How can I do that?

export async function getStaticProps(context) {
  const fund = context.params.fund;

  const avggReturnsRes = await fetch(
    https://localhost:8000/avggaut/?name=${fund}
  );
  const avggReturnsResult = await avggReturnsRes.json();

  const navPlotRes = await fetch(
    https://localhost:8000/navplot/?name=${fund}
  );
  const navPlotResult = await navPlotRes.json();


  return {
    props: {
      fund: fund,
      avggReturnsResult: avggReturnsResult,
      navPlotResult: navPlotResult,
    },
  };
}
2
  • What do you want actually?? Commented Aug 19, 2021 at 8:54
  • What should happen if an error occurs during each API call? Commented Aug 19, 2021 at 17:46

1 Answer 1

1

wrap your fetch calls in a try-catch block and, generally if the first request fails then control directly jumps to catch block without executing the second fetch

export const getStaticProps = async () => {
  try {
    const res = await fetch('https://example.com');
    const data = await res.json()
    if (!data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch () {
    return { notFound: true };
  }
};

If you really want to separate each request you can put them in separate try-catch blocks, although there is no reason to do that since try-catch catches only one error at a time, nevertheless, you can do this


export const getStaticProps = async () => {
  // first requst
  try {
    const res = await fetch('https://url2.com');
    const data = await res.json()
    if (!data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch (err) {
    return { notFound: true };
  }

  // Second request
  try {
    const res = await fetch('https://url2.com');
    const data = await res.json()
    if (!data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch (err) {
    return { notFound: true };
  }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.