PRASANTH BATTULA
PRASANTH BATTULA

Reputation: 57

Handle errors of API call in getStaticProps in NextJS

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,
    },
  };
}

Upvotes: 0

Views: 5708

Answers (1)

sairaj
sairaj

Reputation: 413

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 };
  }
};

Upvotes: 1

Related Questions