如何干净地处理 nextjs getStaticProps 中的错误

问题描述

我目前正忙于构建我的第一个 Next.JS 应用程序(Next 和 Strapi)。现在一切正常,但我很好奇在使用 getStaticProps 时实现错误处理的最佳方法是什么。

我自己尝试了一些东西(传递多个道具等,但都不起作用(典型的未序列化 JSON 错误)。我想要实现的是页面本身上的错误消息(例如 /about)找到了数据。附加了错误消息(状态码)。

我希望这是可能的,我做了很多研究并发现:https://github.com/vercel/next.js/pull/17755 这个。但这并不是我要找的。​​p>

谢谢。 贾斯汀·斯派克博斯

解决方法

您可以创建custom 404 and 500 error pages。有一个显示 statusCode 的选项,但是您可以通过在 notfound: true 中返回 getStaticProps 来告诉 Next 使用 404 页面。

如果您返回 notfound: true,statusCode 将始终显示 404 页面,并且您知道状态代码将为 404。

以下是在 getStaticProps 中捕获错误的示例 - 这将生成您的页面或显示根据您的规范设计的自定义错误页面。

export const getStaticProps = async () => {
  try {
    const { data,errors } = await someQuery();
    if (errors || !data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch () {
    return { notFound: true };
  }
};