【问题标题】:Handle errors of API call in getStaticProps in NextJS在 NextJS 的 getStaticProps 中处理 API 调用的错误
【发布时间】:2021-10-20 23:11:41
【问题描述】:

我在 getStaticProps 中有多个 API 调用。我想单独处理每个 API 调用的错误。我该怎么做?

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

【问题讨论】:

  • 你到底想要什么??
  • 每次API调用出现错误怎么办?

标签: next.js fetch getstaticprops


【解决方案1】:

将您的 fetch 调用包装在 try-catch 块中,通常如果第一个请求失败,则控制直接跳转到 catch 块而不执行第二个 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 };
  }
};

如果你真的想分离每个请求,你可以将它们放在单独的 try-catch 块中,尽管没有理由这样做,因为 try-catch 一次只捕获一个错误,但是,你可以这样做


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

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 2021-07-14
    • 1970-01-01
    • 2021-11-13
    • 2021-11-03
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多